I have an entity class which includes many fields. To make it simple, let's assume the class is defined as following:
public partial class Branches
{
public int num { get; set; }
public string name { get; set; }
public string street { get; set; }
public string city { get; set; }
In my API class, I want to define a function for updating a record of this type. As creating a function to update each field separately seems like quite an overhead for my application, I decided to define one function that updates all fields. Can I assign the object received by the function directly to the object used for the update as following?
void updateBranch(Branches branch)
{
using (var dbContext = new entitiesContext())
{
var result = dbContext.Branches.SingleOrDefault(b => b.num == branch.num);
if (result != null)
{
**result = branch;**
dbContext.SaveChanges();
}
}
}
I'm using Entity Framework version 6.0
Yes you can use it, with the following code
void updateBranch(Branches branch)
{
using (var dbContext = new entitiesContext())
{
dbContext.Branches.Attach(branch);
dbContext.Entry(branch).State = EntityState.Modified;
dbContext.SaveChanges();
}
}
When you attach a Entity to DBContext, Entity Framework is aware that this instance exist in database and will perform an update operation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.