gpt4 book ai didi

c# - 实体在我想要附加时插入

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:55 25 4
gpt4 key购买 nike

我有两个类:

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

[Required]
[MaxLength(10)]
public string PartNumber { get; set; }

[Required]
public virtual Module Module { get; set; }
}

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

[Required]
[MaxLength(10)]
public string Name { get; set; }
}

然后我尝试执行此操作:

PartDefinition part = new PartDefinition(partNumber, module);
context.PartDefinitions.Add(part);
context.SaveChanges();

我传递给新零件定义的模块已经存在于数据库中。但是,当我保存新部件定义而不是将当前模块添加为外键时,它会插入一个全新的模块。

我怎样才能改变这个?

最佳答案

因为您没有任何表示数据库中主键的 [Key] 属性;它每次都会添加一个新模块。尝试使用 [Key] 属性标记 Id 属性。还尝试在获取模块和插入部分时使用相同的上下文实例。

关于c# - 实体在我想要附加时插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10552415/

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