How to operate on the table many to many EF - asp.net-mvc

I am working with ASP.NET MVC and I am using Entity Framework. While generating my database which has been created by DataBase First I got this relation which is shown below. My question is: how can I assign a role for a particular patient?

This slightly depends on how your project is structured, and any design patterns you're using, but the below code should point you in the right direction.
// query the DB for existing patient/role
var dbContext = new MyDbContext()
var patient = dbContext.Set<Patient>().FirstOrDefault(x => x.PatientID = patientId);
var role = dbContext.Set<Role>().FirstOrDefault(x => x.RoleID = roleId);
patient.Roles.Add(role);
dbContext.SaveChanges();
EDIT
Or something like this for a new instance of a patient...
var newPatient = new Patient {
Name = "NameHere"
....
};
newPatient.Roles.Add(role);
dbContext.Entry(newPatient).State = System.Data.EntityState.Added;
dbContext.SaveChanges();

Related

Updating database with Entity Framework, Comparing methods

I think these are essentially the same method, but the first one queries the db first, so has less performance due to hitting the db twice. I will only have 40 users at most so performance isn't too big an issue. Is there any other reason to use one over the other?
Grab the entity from the db first, change it then save it:
public void UpdateStudent(StudentModel model)
{
using (var _db = new AppEntities())
{
Student student = new Student();
student = _db.Student.Find(model.studentId);
student.FirstName = model.FirstName;
student.LastName = model.LastName;
student.DOB = model.DOB;
student.GradeId = model.GradeId;
_db.Entry(student).State = System.Data.Entity.EntityState.Modified;
_db.SaveChanges();
}
}
Change the entity and let EF find it in the DB and update:
public void UpdateStudent(StudentModel model)
{
using (var _db = new AppEntities())
{
Student student = new Student()
{
student.StudentId = model.StudentId,
student.FirstName = model.FirstName,
student.LastName = model.LastName,
student.DOB = model.DOB,
student.GradeId = model.GradeId
};
_db.Entry(student).State = System.Data.Entity.EntityState.Modified;
_db.SaveChanges();
}
}
In first code snippet you take some version of entity form db. If other thread or proccess modifies the same entity I don't think EF would let you just do an update as your base version of entity differs from that one in db right before an update query.
In the second one if some thread or process modifies this entity while you're processing this request you probably could lose that change.
EDIT: I never tired that. I'm always getting the entity and then modify and save but you could write a test to verify what happens.
In your first snippet, you don't have to mark the entity as Modified, because the change tracker takes care of that. This is important to note because it also defines the difference between the two methods. I'll explain.
Let's assume that of all assignments (student.FirstName = model.FirstName; etc.) only the first one is a real change. If so -
The first code fragment (but without marking the entity as Modified) triggers an update statement that only updates FirstName.
The second code fragment always updates all fields in Student.
This means that the first fragment is less likely to cause concurrency conflicts (someone else may change LastName in the mean time and you don't overwrite this modification by stale data, as happens in the second scenario).
So it's about fine-grained changes vs. a sweeping update, roundtrips vs. redundancy:
the first scenario takes roundtrips but is more concurrency-safe.
the second scenario takes no roundtrips but is less concurrency-safe.
It's up to you to balance the trade-offs.
To make this choice a little bit harder, there is a third option:
public void UpdateStudent(StudentModel model)
{
using (var _db = new AppEntities())
{
Student student = new Student()
{
student.StudentId = model.StudentId,
student.FirstName = model.FirstName,
student.LastName = model.LastName,
student.DOB = model.DOB,
student.GradeId = model.GradeId
};
_db.Students.Attach(student);
_db.Entry(student).Property(s => s.FirstName).IsModified = true;
_db.Entry(student).Property(s => s.LastName).IsModified = true;
_db.Entry(student).Property(s => s.DOB).IsModified = true;
_db.Entry(student).Property(s => s.GradeId).IsModified = true;
_db.SaveChanges();
}
}
No roundtrip and now you only mark 4 properties as modified. So you still update too many properties if only one was actually changed, but four is better than all.
And there's more to this "rondtrips vs redundancy" question, but I explained that elswhere.

SimpleMembership MVC 4 get data from UserProfile having role in webpages_Roles

I have the following code. But there must be a more database efficient way to do this, because, correct me if Im wrong the number of database queries is
(1 + (qty of users with admin role))
With a new MVC 4 project the membership defaults are the tables UserProfile, webpages_Roles and webpages_UsersInRoles. I see lots of built in methods for Roles.Get*. If I want to avoid writing code like what I have below do I need to explicitly create a model for webpages_Roles and webpages_UsersInRoles as well as all the code first properties? Getting just the username from Roles.Get* doesnt suffice, I need the full UserProfile.
FYI the "UserRole" object below is just an enum
public ActionResult Admins()
{
var dbContext = new UsersContext();
var usernames = Roles.GetUsersInRole(UserRole.SiteAdministrator.ToString());
var adminUsers = new List<UserProfile>();
foreach (string username in usernames)
{
var adminUser = dbContext.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == username);
adminUser.Roles.Add(UserRole.SiteAdministrator);
adminUsers.Add(adminUser);
}
return View(adminUsers);
}
Yes, you don't want to do it that way. That's a very inefficient way.
Instead, use the tools as they were designed. For example, something like this:
var usernames = Roles.GetUsersInRole(UserRole.SiteAdministrator.ToString());
var adminUsers = dbContext.UserProfiles
.Where(x => usernames.Contains(x.Username)).ToList();
return View(adminUsers);

How do I gracefully reattach an Entity Framework 5 POCO structure and save it?

I am making an MVC4 web application using Entity Framework 5 (Database-first with generated POCOs) for data access.
In the app, the user goes through several screens, creating or editing a document (called a 'case study'). When they arrive at the final screen, their document exists as a CaseStudy POCO in memory, and everything is great until it is time to save this structure to the database.
To store the document, I have defined several database tables, which in turn map to EF POCOs used by the business layer, which is then consumed by the MVC controllers. As such, short-lived DbContexts are used to retrieve POCOs and store them in session between requests.
As a result, the save screen must save the contents of this POCO that has navigational properties to existing table data (Category, Layout, and Sections tables), and also added or updated data (CaseStudySections and the CaseStudy itself). So all of the POCOs are either new, or the context used to retrieve them has long been disposed. In other words, they are all 'detached'.
What is unusual about this post is that I already have a working solution in hand. The problem is that it is bulky, brittle, and inelegant. I am posting the code below. Note the iteration through sub-collections, the explicit adds and attaches, having to get an entry object and mark individual properties as modified just so they will be updated, and the awful song and dance at the end to get the AdditionalMaterials collection synced up. If this is what is required to deal with detached POCOs in EF5 I will be disappointed.
Am I missing something here? Is this consistent with best practices? Is there a more graceful and/or concise way to attach a structure of POCOs and insert/update?
The code to save a case study:
public void SaveCaseStudy(CaseStudy caseStudy)
{
foreach (var s in caseStudy.CaseStudySections)
{
this.Entities.Sections.Attach(s.Section);
if (s.CreatedByRefId == default(Guid))
{
s.CreatedByRefId = this.UserRefId;
s.CreatedTime = DateTime.Now;
this.Entities.CaseStudySections.Add(s);
}
else
{
this.Entities.CaseStudySections.Attach(s);
var entry = this.Entities.Entry(s);
entry.Property(e => e.TextData).IsModified = true;
entry.Property(e => e.BinaryData).IsModified = true;
}
s.LastModifiedByRefId = this.UserRefId;
s.LastModifiedTime = DateTime.Now;
}
foreach (var m in caseStudy.AdditionalMaterials)
{
if (m.CreatedByRefId == default(Guid))
{
m.CreatedByRefId = this.UserRefId;
m.CreatedTime = DateTime.Now;
this.Entities.AdditionalMaterials.Add(m);
}
else
{
this.Entities.AdditionalMaterials.Attach(m);
}
m.LastModifiedByRefId = this.UserRefId;
m.LastModifiedByTime = DateTime.Now;
}
this.Entities.Layouts.Attach(caseStudy.Layout);
this.Entities.Categories.Attach(caseStudy.Category);
if (caseStudy.CreatedByRefId != default(Guid))
{
this.Entities.CaseStudies.Attach(caseStudy);
var entry = this.Entities.Entry(caseStudy);
entry.Property(e => e.CaseStudyName).IsModified = true;
entry.Property(e => e.CaseStudyTitle).IsModified = true;
}
else
{
this.Entities.CaseStudies.Add(caseStudy);
caseStudy.CreatedByRefId = this.UserRefId;
caseStudy.CreatedTime = DateTime.Now;
}
caseStudy.LastModifiedByRefId = this.UserRefId;
caseStudy.LastModifiedTime = DateTime.Now;
if (caseStudy.CaseStudyStatus != (int)CaseStudyStatus.Personalized)
{
caseStudy.CaseStudyStatus = (int)CaseStudyStatus.PendingApproval;
}
caseStudy.ApprovedByRefId = null;
caseStudy.ApprovedTime = null;
this.Entities.SaveChanges();
var existingAdditionalMaterialRefIds = caseStudy.AdditionalMaterials
.Select(m => m.AdditionalMaterialRefId)
.ToArray();
var additionalMaterialsToRemove = this.Entities.AdditionalMaterials
.Where(m =>
m.CaseStudyRefId == caseStudy.CaseStudyRefId &&
!existingAdditionalMaterialRefIds.Contains(m.AdditionalMaterialRefId))
.ToArray();
foreach (var additionalMaterialToRemove in additionalMaterialsToRemove)
{
this.Entities.AdditionalMaterials.Remove(additionalMaterialToRemove);
}
this.Entities.SaveChanges();
}
In general it is what you have to do. You must tell EF about each change you want to perform when attaching detached object graph. I don't say that your code cannot be simplified but you will still have to deal with every entity and setting its state if you want it to be added or modified.
Here is little bit older but still valid answer about the topic - in short nothing has changes since I wrote it, only new DbContext API was created which still sits on top of the old API. The best description of this topic I have seen so far is in book Programming Entity Framework: DbContext.
How about just doing:
db.CaseStudies.Attach(caseStudy);
db.Entry(caseStudy).State = EntityState.Modified;
db.SaveChange();
That will save all changes in your model to the db.

Entity Framework - Disconnexted Behavior in nTier

I am new to EF but I will try my best to describe the scenario. I have 3 tables in My DB namely RecommendationTopic, Recommendation and Question. Each RecommendationTopic can have multiple Recommendations and each Recommendation may have multiple questions. Assume that I already have predefined questions in my Question table.
I have one service that returns me list of questions like below:
public List<Question> FetchQuestions(int categoryID)
{
using (Entities context = new Entities())
{
questions = context.Questions.Where(i => i.ID >= 0).ToList();
}
}
I have another service which is used to create RecommendationTopic and Recommendation whose code is something like below:
public void ManageRecommendation(RecommendationTopic recommendationTopic)
{
using (Entities context = new Entities())
{
context.AddObject("RecommendationTopics", recommendationTopic);
context.SaveChanges();
}
}
My client code looks like below:
List<Question> questions;
using (QuestionServiceClient client = new QuestionServiceClient())
{
questions = client.FetchQuestions();
}
using (RecommendationServiceClient client = new RecommendationServiceClient())
{
RecommendationTopic rTopic = new RecommendationTopic();
rTopic.CategoryID = 3;
rTopic.Name = "Topic From Client";
Recommendation rCom = new Recommendation();
rCom.Text = "Dont!";
rCom.RecommendationTopic = rTopic;
rCom.ConditionText = "Some condition";
rCom.Questions.Add(questions[0]);
rCom.Questions.Add(questions[1]);
client.ManageRecommendation(rTopic);
}
Since the client makes 2 separate service calls, the context would be different for both the calls. When I try to run this and check the EF profiler, it not only generates query to insert into RecommendationTopic and Recommendation but also Question table!
I am sure this is caused due to different context for both the calls as when I execute a similar code within a single context, it works as it's supposed to work.
Question is, how do I make it work in a disconnected scenario?
My client could be Silverlight client where I need to fill a Question drop down with a separate call and save Recommendation topic in a separate call. For this reason I am using self tracking entities as well.
Any input appreciated!
-Vinod
If you are using STEs (self tracking entities) your ManageRecommendation should look like:
public void ManageRecommendation(RecommendationTopic recommendationTopic)
{
using (Entities context = new Entities())
{
context.RecommendationTopics.ApplyChanges(recommendationTopic);
context.SaveChanges();
}
}
Calling AddObject skips self tracking behavior of your entity. If you are not using STEs you must iterate through all questions and change their state to Unchanged:
public void ManageRecommendation(RecommendationTopic recommendationTopic)
{
using (Entities context = new Entities())
{
context.RecommendationTopics.AddObject(recommendationTopic);
foreach (var question in recommendationTopic.Questions)
{
context.ObjectStateManager.ChangeObjectState(recommendationTopic, EntityState.Unchanged);
}
context.SaveChanges();
}
}

Linq to SQL update not working using Repository pattern

I am using asp.net mvc for an application. I've taken some guidance from Rob Conery's series on the MVC storefront. I am using a very similar data access pattern to the one that he used in the storefront.
However, I have added a small difference to the pattern. Each class I have created in my model has a property called IsNew. The intention on this is to allow me to specify whether I should be inserting or updating in the database.
Here's some code:
In my controller:
OrderService orderService = new OrderService();
Order dbOrder = orderService.GetOrder(ID);
if (ModelState.IsValid)
{
dbOrder.SomeField1 = "Whatever1";
dbOrder.SomeField2 = "Whatever2";
dbOrder.DateModified = DateTime.Now;
dbOrder.IsNew = false;
orderService.SaveOrder(dbOrder);
}
And then in the SQLOrderRepository:
public void SaveOrder(Order order)
{
ORDER dbOrder = new ORDER();
dbOrder.O_ID = order.ID;
dbOrder.O_SomeField1 = order.SomeField1;
dbOrder.O_SomeField2 = order.SomeField2;
dbOrder.O_DateCreated = order.DateCreated;
dbOrder.O_DateModified = order.DateModified;
if (order.IsNew)
db.ORDERs.InsertOnSubmit(dbOrder);
db.SubmitChanges();
}
If I change the controller code so that the dbOrder.IsNew = true; then the code works, and the values are inserted correctly.
However, if I set the dbOrder.IsNew = false; then nothing happens...there are no errors - it just doesn't update the order.
I am using DebuggerWriter here: http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11 to trace the SQL that is being generated, and as expected, when the IsNew value is true, the Insert SQL is generated and executed properly. However, when IsNew is set to false, there appears to be no SQL generated, so nothing is executed.
I've verified that the issue here (LINQ not updating on .SubmitChanges()) is not the problem.
Any help is appreciated.
In your SaveOrder method you are always creating a new ORDER object. You need to change this so that if order.IsNew is false, it retrieves the existing one from the DB and updates it instead.
public void SaveOrder(Order order)
{
ORDER dbOrder;
if (order.IsNew)
{
dbOrder = new ORDER();
dbOrder.O_ID = order.ID;
}
else
{
dbOrder = (from o in db.ORDERS where o.O_ID == order.ID select o).Single();
}
dbOrder.O_SomeField1 = order.SomeField1;
dbOrder.O_SomeField2 = order.SomeField2;
dbOrder.O_DateCreated = order.DateCreated;
dbOrder.O_DateModified = order.DateModified;
if (order.IsNew)
db.ORDERs.InsertOnSubmit(dbOrder);
db.SubmitChanges();
}
I think you have the problem that your entity is detached from your context.
You should try to attach your entity back to your context if you want to update. The downside of LINQtoSQL is that for the re-attachment you'll need the original state of the object when it was detached...
Another solution is to re-get your entity from the context and copy all the data from your entity in the parameter. This will do until you'll have more complex entities.
What tvanfosson said.
I would just like to add that I use logic where if Id equals default(0 or Empty if using guids), then I assume it is new. Otherwise if I have the id passed in, then I go get the existing object and update it.

Resources