Entity framework one to zero or one relationship without navigation property

爷,独闯天下 提交于 2019-12-02 03:22:05

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

public virtual ICollection<MemberDataSet> MemberDataSets { get; set; }

Does UserProfile have a UserId property?

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