Entity framework one to zero or one relationship without navigation property

前端 未结 1 1572
忘了有多久
忘了有多久 2021-01-25 03:08

I hit an issue when trying to delete records due to FK constraints. I therefore went back to the drawing board and am trying to specify how the relationship should work.

1条回答
  •  礼貌的吻别
    2021-01-25 03:48

    The error

    The ForeignKeyAttribute on property 'DeferredData' on type 'MemberDataSet' is not valid. The foreign key name 'DeferredDataId' was not found on the dependent type 'DeferredData'.

    is telling you exactly what is wrong.

    DeferredData.Id is not DeferredData.DeferredDataId
    

    This is your problem.

    Just removing the attribute will solve your problem as Entity Framework figures out foreign keys based on the name of your entities. If you want to keep the attributes, use:

    [ForeignKey("Id")]
    

    instead of

    [ForeignKey("DeferredDataId")]
    

    So:

    public class MemberDataSet
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    
        public int? DeferredDataId { get; set; }
        [ForeignKey("Id")]
        public virtual DeferredData DeferredData { get; set; }
    }
    

    or change the Id of DeferredData to be DeferredDataId and not Id

    A few notes about EF:

    1. Properties with names Id are automatically Keys, so no need for the Key attribute
    2. When you define a relationship using code first you don't need to manually decorate things with attributes, EF figures it out based on the structure.

    Edit:

    For a One-to-many relationship you need an ICollection

    public virtual ICollection MemberDataSets { get; set; }
    

    Does UserProfile have a UserId property?

    0 讨论(0)
提交回复
热议问题