8

我的问题原来是有两个上下文的。我对我的代码进行了一些修改,使其只有一个上下文,我的问题就消失了。

我有一个用户,它有一个 UserContact 列表,它本身有一个 ContactOption。它是一个相当简单的一对多,多对一,中间有 UserContact 表。

如果我将用户从数据库中拉出并创建一个新的 UserContact,但将 ContactOption 设置为现有项目(我已从数据库中拉出),当我 SaveChanges 时,实体框架会在数据库中创建一个新的 ContactOption本质上是我添加到 UserContact 的副本(除了它获得了一个新的 id)。

我已经为此奋斗了几个小时,但无法弄清楚。有任何想法吗?

我正在为我的数据库查询使用存储库模式,但我确保它们共享相同的上下文。

我用这个把用户从数据库中拉出来:

var user = _context.Users.Include("UserContacts.ContactOption")
              .Where(id => id == 1);

并通过以下方式拉出联系选项:

var co = _context.ContactOptions.FirstOrDefault(c => c.Id == id);

我将 ContactOption 添加到 UserContact 中,如下所示:

var contactOption = _context.ContactOptions.FirstOrDefault(c => c.Id == someId);

var contact = new UserContact { ContactOption = contactOption  };
contact.Data = "someData";

user.UserContacts.Add(contact);

我的模型如下所示:

public class User
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<UserContact> UserContacts { get; set; }
}

public class UserContact
{
    [Key]
    public int Id { get; set; }

    [Required]
    public User User { get; set; }

    [Required]
    public ContactOption ContactOption { get; set; }
    public string Data { get; set; }
}

public class ContactOption
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}
4

2 回答 2

2

我运行您的代码并得到了确切的预期结果: UserContacts表中的新行具有现有的 UserId 和 ContactOptionId,所以我不确定那里发生了什么,但您可以尝试在 UserContact 对象中显式地使用 FK,这样您就可以完全控制 Code First 如何为您插入记录。为此,您需要按如下方式更改 UserContact:

public class UserContact
{
    public int Id { get; set; }

    // By Convention these 2 properties will be picked up as the FKs: 
    public int UserId { get; set; }
    public int ContactOptionId { get; set; }

    [Required]
    public User User { get; set; }        
    [Required]
    public ContactOption ContactOption { get; set; }

    public string Data { get; set; }
}

然后你可以像这样改变你的代码:

var contactOption = _context.ContactOptions.Find(someId);
var user = _context.Users.Find(1);

var contact = new UserContact 
{ 
    ContactOptionId = contactOption.Id,  
    UserId = user.Id,
    Data = "someData"
};

user.UserContacts.Add(contact);
context.SaveChanges();
于 2010-11-14T01:17:43.967 回答
1

我的问题原来是有两个上下文的。我对我的代码进行了一些修改,使其只有一个上下文,我的问题就消失了。感谢 Morteza Manavi 为我指明了正确的方向。

于 2010-11-14T14:21:06.787 回答