问题
My business has a method which creates a MailMessage from an email. The method I use gets an Email object as a parameter, which is a simple POCO object, the foreign key properties like ToId and FromId are already set on it. The entity also have navigation properties to EmailAddress entities (FromEmailAddress and ToEmailAddress).
What I want to achive is to use these navigation properties. The way I was able to this is the following, but it looks like a hax:
public MailMessage CreateEmail(Email email)
{
var tmpEmail = db.Set<Email>().Create();
db.Emails.Add(tmpEmail);
db.Entry<Email>(tmpEmail).CurrentValues.SetValues(email);
db.SaveChanges();
email = tmpEmail;
And then I use the email in my code. This way the entity has a proxy now so I am able to use navigation properties. Are there any simpler way to do this?
回答1:
It's a good solution in my opinion to enable lazy loading. An alternative would be to load the navigation properties explicitely. Then you don't need to create a proxy:
public MailMessage CreateEmail(Email email)
{
db.Emails.Add(email);
db.SaveChanges();
db.Entry(email).Reference(e => e.FromEmailAddress).Load();
db.Entry(email).Reference(e => e.ToEmailAddress).Load();
//...
}
It creates two roundtrips to the database - the same when you use lazy loading and access the navigation properties.
来源:https://stackoverflow.com/questions/7969451/entity-framework-use-navigation-properties-on-newly-created-entity