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?
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:
It creates two roundtrips to the database – the same when you use lazy loading and access the navigation properties.