使用实体框架更新外键

时间:2017-07-24 11:19:56

标签: entity-framework ef-code-first

我正在尝试更新名为(Friendship)的表中的外键。外键是名为(FriendshipStatus)的表,问题是所有值都被更新,但外键除外。我使用代码第一种方法。

友谊班

public class Friendship
{
    public int Id { get; set; }
    public User UserOne { get; set; }
    public User UserTwo { get; set; }
    public FriendshipStatus Status { get; set; }
    public User ReqSB { get; set; }
    public RelationType RelationType { get; set; }
    public Relationship Relationship { get; set; }
    public DateTime FriendshipDate { get; set; }



}

FriendshipStatus类

public class FriendshipStatus
{
    public int Id { get; set; }
    public string Name { get; set; }
}

以下是更新的代码

 using (context)
        {


            Friendship f = getFrienshipRecord(u1, u2); // get single record from db which is to be updated
            if (f != null)
            {
                Friendship ff = new Friendship();
                ff.Status = new FriendshipStatus() { Id = 2}; //actually wants to update this this field
                ff.Id = f.Id;
                ff.FriendshipDate = DateTime.Now;

                context.Entry(ff).State = EntityState.Modified;
                context.SaveChanges();


            }

        }

上面的代码更改了日期时间,但它不会更改外键。

1 个答案:

答案 0 :(得分:1)

这是我用于包含孩子的更新的技术。首先,我喜欢将外键公开为父级的一部分。如果您将其命名为FriendshipStatusId,EF将自动建立关联,或者您可以添加注释或流畅代码(如果愿意):

public class Friendship
{
    public int Id { get; set; }
    public User UserOne { get; set; }
    public User UserTwo { get; set; }

    public int? FriendshipStatusId { get; set; }  // optional FK
    public FriendshipStatus Status { get; set; }

    public User ReqSB { get; set; }
    public RelationType RelationType { get; set; }
    public Relationship Relationship { get; set; }
    public DateTime FriendshipDate { get; set; }
}

现在,您可以通过简单地获取实体(将其置于跟踪中)并更新FK来进行更新:

using (context)
{
    Friendship f = getFrienshipRecord(u1, u2); // get single record from db which is to be updated
    if (f != null)
    {
        f.FriendshipDate = DateTime.Now;
        f.FriendshipStatusId = 2;
        context.SaveChanges();
    }
}

请注意,如果添加FK,则可能需要执行迁移或重新生成数据库,因为EF默认值可能类似于FriendshipStatus_Id。

相关问题