Entity framework use navigation properties on newly created entity

雨燕双飞 提交于 2019-12-11 13:41:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!