C# 实体框架多个一对一关系
我在为引用三个可能实体之一的实体设置外键时遇到问题。课程如下:C# 实体框架多个一对一关系,c#,entity-framework,ef-code-first,entity-framework-6,C#,Entity Framework,Ef Code First,Entity Framework 6,我在为引用三个可能实体之一的实体设置外键时遇到问题。课程如下: public class Target { public int Id { get; set; } public int? AttachmentId { get; set; } public virtual Attachment Attachment { get; set; } } public class SubTarget { public int Id { get; set; } pub
public class Target
{
public int Id { get; set; }
public int? AttachmentId { get; set; }
public virtual Attachment Attachment { get; set; }
}
public class SubTarget
{
public int Id { get; set; }
public int? AttachmentId { get; set; }
public virtual Attachment Attachment { get; set; }
}
public class Procedure
{
public int Id { get; set; }
public int? AttachmentId { get; set; }
public virtual Attachment Attachment { get; set; }
}
public class Attachment
{
public int Id { get; set; }
public int? TargetId { get; set; }
public int? SubTargetId { get; set; }
public int? ProcedureId { get; set; }
public virtual Target Target { get; set; }
public virtual SubTarget SubTarget { get; set; }
public virtual Procedure Procedure { get; set; }
}
因此,前三个类中的每一个都可能有或可能没有附件
,而每个附件
都可以而且必须引用前三个类中的一个。首先:像这样设置外键有可能吗?
其次:如何通过代码优先迁移来实现它?
在当前的设置中,我得到一个错误,指出“无法确定外键关系的主端”,并且通过注释
附件
类中的虚拟属性,关系似乎倒退,例如,Target
有一个外键,该外键引用了附件
如果您想在EF中有一对一的关系,请将此注释添加到Target、SubTarget和Procedure类中:
[Key, ForeignKey("Attachments")]
public int Id {get;set;}
这将使主键与外键相同。
然后从这3个类中删除:
public int? AttachmendId {get;set;}
希望你能得到这份工作。我经常在一对一的关系中挣扎,所以我基本上将我的表设计为一对零或一对多。
如果您需要更多关于一对一关系的信息,请查看此处
检查这些链接:尝试了这个,但没有达到预期效果。我在表中还有其他几个FK关系,在这一点上更改模式毕竟不是那么简单。但是,我也怀疑这个解决方案会导致这样一种情况,
附件必须引用所有3个其他类。我用这些属性重建了数据库,正如我所想,它现在需要附件
类上的所有3个引用。所以,这没有帮助..如果你只是删除所有引用回到附件呢?只需要将外键附加到其他类?