I see a lot of examples on using EF code first with POCOs that show something like this:
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
Now, look at the Blog
property. Should not it be like this instead:
private Blog blog;
public virtual Blog Blog
{
get
{
return blog;
}
set
{
blog = value;
if (blog != null)
{
BlogId = blog.BlogId;
}
}
}
I mean, since you already are "polluting" your model with the foreign key, should not you at least keep it in sync with the reference? Or you should not rely on BlogId
when reading data anyway (eg. like you want to know if a specific BlogId
is on a list). Or maybe there is a magic property on DbContext
(like KeepForeingKeysPropertiesSyncronizedWithReferences
) that does that to me and I am the only sad programmer that are woried about this? Or am I paranoid? (also, sorry for my poor english)
EDIT
Sorry for that - this really was a stupid question. Stefan is right, EF really does this for you. I wasn't seen this because the references I was passing was loaded with AsNoTracking()
. Only in this condition you will have a reference with ID and the foreing key field will be 0. As long as you pass a reference that is already on the context, it should work.
You don't need to do this per se, EF does this for you.
If you set the independent association property, EF will synchronize the foreign key property to reflect your change and vice versa. It doesn't happen immediately automatically mind you, I think this happens after calling SaveChanges but I'm not sure.
If you want to know why some people use the foreign key property: it's more convenient in detached apps like web apps. When you need to scale your app, it can also help to improve performance (read this in a recent MS blog post somewhere).
Basically, you only need to do this yourself if you're mixing and matching; when in one method you're using the independent association property and in another you're using the foreign key property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With