在新成立的实体,实体框架使用的导航性能 [英] Entity framework use navigation properties on newly created entity

查看:86
本文介绍了在新成立的实体,实体框架使用的导航性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的生意不但创造从电子邮件MailMessage的方法。我使用的方法获取一个Email对象作为参数,这是一个简单的POCO对象,外键属性,如TOID和FromId已经设置就可以了。该实体还具有导航属性EmailAddress的实体(FromEmailAddress和ToEmailAddress)。

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).

我想才达到是使用这些导航属性。我的样子能这是下面的,但它看起来像一个HAX:

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;

然后我在code使用的电子邮件。这样,实体有一个代理,所以我现在我能够使用的导航性能。有没有更简单的方法来做到这一点?

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?

推荐答案

这是在我看来,一个良好的解决方案,使延迟加载。另一种方法是,以明确地加载导航属性。然后,你并不需要创建一个代理:

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.

这篇关于在新成立的实体,实体框架使用的导航性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆