gpt4 book ai didi

c# - Entity Framework Code First 多对多创建重复行

转载 作者:太空狗 更新时间:2023-10-29 19:44:36 25 4
gpt4 key购买 nike

我的问题原来是有两个上下文。我稍微修改了我的代码,使其只有一个上下文,然后我的问题就消失了。

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

如果我将用户从数据库中拉出并创建一个新的 UserContact,但将 ContactOption 设置为现有项目(我已将其从数据库中拉出),当我保存更改时, Entity Framework 会在基本上是我添加到 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; }
}

最佳答案

我运行你的代码并得到了准确的预期结果: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();

关于c# - Entity Framework Code First 多对多创建重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com