我的生意不但创造从电子邮件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.