问题描述
以下是今天的早期帖子:
Following on from earlier posts today:
我现在正在尝试配置以下关系:
I'm now trying to configure the following relationships:
Item1具有可选的RawData
Item2具有可选的RawData
Item3具有可选的RawData
Item1 has optional RawDataItem2 has optional RawDataItem3 has optional RawData
RawData必须附加到Item1,Item2或Item3-不应单独存在。
RawData must be attached to either Item1, Item2 or Item3 - it would not be expected to exist on its own.
当前结构为:
class ItemX
{
[Key]
public int Id { get; set; }
public int? RawDataId { get; set; }
[ForeignKey("RawDataId")]
public virtual RawData RawData { get; set; }
}
public class RawData
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
//other properties
}
我认为这是可以使用以下命令进行配置:
I thought this might be configured using:
modelBuilder.Entity<Item1>().HasOptional(d => d.RawData).WithOptionalPrincipal().WillCascadeOnDelete(true);
modelBuilder.Entity<Item2>().HasOptional(d => d.RawData).WithOptionalPrincipal().WillCascadeOnDelete(true);
modelBuilder.Entity<Item3>().HasOptional(d => d.RawData).WithOptionalPrincipal().WillCascadeOnDelete(true);
但这给出了以下错误:
这是相同的错误我今天在较早的职位上处理过。在这种情况下,我了解了由于共享主键而无法使用的原因。但是在本例中情况并非如此,因为RawData不能与Item1共享主键,因为Item2可能具有相同的ID。
This is the same error I was dealing with in an earlier post today. In that one I understand the reason it wasn't working due to a shared primary key. But that can't be the case in this example as RawData can't share a primary key with Item1 as Item2 might have the same id.
感谢您的帮助。
编辑
我已经使用:
modelBuilder.Entity<Item1>().HasOptional(d => d.RawData).WithMany().HasForeignKey(d=>d.RawDataId).WillCascadeOnDelete(true);
//etc.
数据库看起来不错。将其描述为WithMany似乎有些奇怪,但这也许是多重关系所必需的?
Database looks ok. Seems a little odd to be describing as WithMany though but perhaps this is what is required when then are multiple relationships??
推荐答案
您需要在RawDataclass中包含Item1,Item2和Item3:
You need to include Item1, Item2, and Item3 in the RawDataclass:
public class RawData
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual Item1 i1 {get;set;}
public virtual Item2 i2 {get;set;}
public virtual Item3 i3 {get;set;}
//other properties
}
这篇关于在表实体框架之间配置多个1到0..1关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!