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
4.0k views
in Technique[技术] by (71.8m points)

c# - Will setting EntityState.Modified on root object add any new objects to database?

I'm using EntityFramework to link my C#/WPF project to a SQL Server database. I have an object that has navigational properties to other types of objects (so linking to other tables in the DB).

If I create a new object for one of these navigational properties, and add it to the root object, what is the best way to get this added to the DB without having to check all of the existing properties and compare them to this new object?

MyTable obj = (from myTableObject in db.MyTable select myTableObject).FirstOrDefault();
obj.FirstNavProperties.Add(new FirstNavProperty());
db.Entry(obj).State = EntityState.Modified;

Will the above code add the new FirstNavProperty?


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

1 Reply

0 votes
by (71.8m points)

When you use Add() you don't change MyTable table, you are adding a new record to FirstNavProperties table. The obj.FirstNavProperties just keeps an address of FirstNavProperties List inctance. Add() automaticaly changes state of FirstNavProperties to Added. So remove:

 db.Entry(obj).State = EntityState.Modified; 

from your code. You can call db.SaveChanges() instead.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...