Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...