我在使用Entity Framework的ASP网络CORE MVC网站上工作,我在两个表之间有双重关系:
的DocType
#DocTypeName
#DocTypeValidationText
TraductionInterface
+ ID
DocTypeName和DocTypeValidationText是 TraductionInterface 表的ForeignKey:一个 DocType 有2个 TraductionInterface
这是我的班级:
DocType.cs
public class DocType
{
[Key]
public int DocTypeID { get; set; }
[Required]
public int DocTypeName { get; set; }
[ForeignKey("DocTypeName")]
public virtual TraductionInterface TraductionInterfaceName { get; set; }
[Required]
public int DocTypeValidationText { get; set; }
[ForeignKey("DocTypeValidationText")]
public virtual TraductionInterface TraductionInterfacevalidationText { get; set; }
}
TraductionInterface.cs
public class TraductionInterface
{
[Key]
public int TraductionInterfaceID;
[ForeignKey("DocTypeName")]
public virtual DocType DocTypeName { get; set; }
[ForeignKey("DocTypeValidationText")]
public virtual DocType DocTypeValidationText { get; set; }
}
ApplicationDbContext.cs
builder.Entity<DocType>().ToTable("DocType").HasOne(d => d.TraductionInterfaceName).WithOne(t => t.DocTypeName);
builder.Entity<DocType>().HasOne(d => d.TraductionInterfacevalidationText).WithOne(t => t.DocTypeValidationText);
但是当我尝试更新
时出现此错误无法在实体类型“TraductionInterface”上为属性“DocTypeValidationText”调用Property,因为它已配置为导航属性。属性只能用于配置标量属性。
修改
@ user1672994的解决方案似乎解决了问题,但只应用了第一个关系:
如果
builder.Entity<DocType>().ToTable("DocType").HasOne(d => d.TraductionInterfaceName).WithOne(t => t.DocTypeName);
是在之前
builder.Entity<DocType>().HasOne(d => d.TraductionInterfacevalidationText).WithOne(t => t.DocTypeValidationText);
TraductionInterfaceName
关系适用,否则为TraductionInterfacevalidationText
关系。我怎样才能使这两个关系一起工作?
答案 0 :(得分:1)
错误本身表明您应该定义标量属性并定义ForeignKey
关系。下面的代码定义了关系属性,并在附加ForeignKey
关系
public class TraductionInterface
{
[Key]
public int TraductionInterfaceID {get; set; }
public int DocTypeNameId {get; set; }
[ForeignKey("DocTypeNameId")]
public virtual DocType DocTypeName { get; set; }
public int DocTypeValidationTextId {get; set; }
[ForeignKey("DocTypeValidationTextId")]
public virtual DocType DocTypeValidationText { get; set; }
}