Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I keep foreign keys in sync with references when using POCOs

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.

like image 336
user1526627 Avatar asked Aug 30 '12 07:08

user1526627


1 Answers

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.

like image 92
Stefan Billiet Avatar answered Oct 10 '22 00:10

Stefan Billiet