Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

c# - LINQ to Entities how to update a record

Okay, so I'm new to both EF and LINQ. I have figured out how to INSERT and DELETE but for some reason UPDATE seems to escape my grasp.

Here is a sample of my code:

EntityDB dataBase = new EntityDB();
Customer c = new Customer
{
     Name = "Test",
     Gender = "Male
};
dataBase.Customers.AddObject(c);
dataBase.SaveChanges();

The above creates and adds a record just fine.

Customer c = (from x in dataBase.Customers
             where x.Name == "Test"
             selext x).First();
dataBase.Customers.DeleteObject(c);
dataBase.SaveChanges();

The above effectively deletes the specified record.

Now how do I update? I can't seem to find an "UpdateObject()" method on the entity collection.

question from:https://stackoverflow.com/questions/4617827/linq-to-entities-how-to-update-a-record

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just modify one of the returned entities:

Customer c = (from x in dataBase.Customers
             where x.Name == "Test"
             select x).First();
c.Name = "New Name";
dataBase.SaveChanges();

Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...