简体   繁体   中英

Entity Framework relations questions

I have three classes

public class SPR
{
    public int ID { get; set; }     
    public string SubmittedBy { get; set; }
    public virtual ICollection<SPRItem> AllItems { get; set; }


}
public class SPRItem
{
    [Key]
    public int ID { get; set; }

    public string manufacturer { get; set; }   

    [ForeignKey("SPRItemDetails")]
    public virtual SPRItemDetails ItemDetails { get; set; }      

    public string requestedMinimumQuantity { get; set; }

    public virtual SPR SPR { get; set; }

}


public class SPRItemDetails
    {
        public int ID { get; set; }

        public string ItemNumber { get; set; } 

        public virtual SPRItem SPRItem { get; set; }  


    }

So the SPR class has a collection of SPRItem and which has the ItemDetails object.

I have a web API method which maps the data to the SPR object and fills in the SPRItem list and ItemDetails object. But whenever I am trying to save it using Entity Framework code first I am getting this error

{"Message":"An error has occurred.","ExceptionMessage":"Unable to determine the principal end of an association between the types 'SharePoint.MultiSPR.Service.Models.SPRItemDetails' and 'SharePoint.MultiSPR.Service.Models.SPRItem'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

This is my Context

public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPR> SPRs { get; set; }

    public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPRItem> SPRItem { get; set; }

    public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPRItemDetails> SPRItemDetails { get; set; }

Can someone please tell me how to configure the relations correctly.

Thanks

In a 1:1 relation you always have to indicate the principal and the dependent entity. The principal entity is the one that is most independent of the other, in this case SPRItem , presumably.

Next thing to decide is whether the relationship should be optional or required. I think, judging by the entity names, an SPRItemDetails will never exist without an SPRItem , so the relationship is 1:0..1 (not 0..1:0..1 ). Here's how to configure that:

modelBuilder.Entity<SPRItem>()
            .HasOptional(si => si.ItemDetails)
            .WithRequired(id => id.SPRItem);

This creates (or requires) an SPRItemDetails table having a primary key that's also a foreign key to SPRItem .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM