Configuring multiple 1 to 0..1 relationships between tables entity framework

て烟熏妆下的殇ゞ 提交于 2019-12-12 02:32:29

问题


Following on from earlier posts today:

Entity framework one to zero or one relationship without navigation property

Understanding ForeignKey attribute in entity framework code first

I'm now trying to configure the following relationships:

Item1 has optional RawData Item2 has optional RawData Item3 has optional RawData

RawData must be attached to either Item1, Item2 or Item3 - it would not be expected to exist on its own.

Current structure is:

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);

But this gave the following error:

The ForeignKeyAttribute on property 'RawData' on type 'Item1' is not valid. The foreign key name 'RawDataId' was not found on the dependent type 'RawData'.

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.

Thanks for any help.

Edit

I've got it working using:

modelBuilder.Entity<Item1>().HasOptional(d => d.RawData).WithMany().HasForeignKey(d=>d.RawDataId).WillCascadeOnDelete(true);
//etc.

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??


回答1:


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
}


来源:https://stackoverflow.com/questions/21861097/configuring-multiple-1-to-0-1-relationships-between-tables-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!