开发者

EF4.1 Code First Add Entity with Related Entity

I'm using EF4.1 Code First. I can't get a very simple insert to save the related entity ID. The generated SQL always inserts NULL for any related entities. Example code is below. Can anyone see what I'm doing wrong here? It does properly insert non-entity properties, such as strings. Also I have similar code in a DB initializer class to seed test data and it seems to work fine.

        using (var ctx = new DataContext())
        {
            ctx.Users.Attach(existingUser);

            // create item and add to context
            var newItem = new MyItem();
            ctx.MyItems.Add(newItem);

            // set related e开发者_开发知识库ntity
            newItem.CreatedBy = existingUser;

            ctx.SaveChanges();
        }


Your code should work with default configuration of your DbContext. One possible explanation that it does not work is that you have automatic change detection disabled, for instance if you have in your context's constructor something like:

public DataContext()
{
    this.Configuration.AutoDetectChangesEnabled = false;
}

In this case EF would not detect the change of the navigation property newItem.CreatedBy after you have added the new item to the context. (SaveChanges would detect this last change if change detection isn't disabled.)

You can change your code so that setting the navigation property happens before you add the new item to the context:

using (var ctx = new DataContext())
{
    ctx.Users.Attach(existingUser);

    // create item and add to context
    var newItem = new MyItem();

    // set related entity
    newItem.CreatedBy = existingUser;

    ctx.MyItems.Add(newItem);

    ctx.SaveChanges();
}

This should work with and without automatic change detection.


Try this:

using (var ctx = new DataContext())
{
    ctx.Users.Attach(existingUser);

    // create item and add to context
    var newItem = new MyItem();
    ctx.MyItems.Add(newItem);

    // set related entity
    newItem.CreatedBy = existingUser;

    // Added
    ctx.ObjectStateManager.ChangeObjectState(newItem.CreatedBy, EntityState.Added);

    ctx.SaveChanges();
}

If that doesn't work, change the line with:

ctx.ObjectStateManager.ChangeObjectState(newItem.CreatedBy, EntityState.Modified);

Added 1 line... Hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜