开发者

Entity Framework One-To-One relationship

I have the following view

开发者_开发技巧vw_Resources
-> ResourceId
-> Name
-> ReportsTo (maps to ResourceId)

and the class

public class Resource
{
     public int ResourceId{get;set;}
     public string Name{get;set;}
     public Resource ReportsTo{get;set;}
}

and the DbContext

public class MyContext
{
     public DbSet<Resource> Resources { get; set; }
}

How do I map the ReportsTo so that the DbContext returns a Resource object. I have to do this in the following method in the DbContext class using the ModelBinder

protected override void OnModelCreating(DbModelBuilder modelBuilder)


The following mapping worked

modelBuilder.Entity<Resource>().HasRequired(r => r.ReportsTo).WithMany().Map(r => r.MapKey("ReportsTo"));


modify your entity like this

public class Resource
{
     public int ResourceId{get;set;}
     public string Name{get;set;}
     public int? ReportsToId{get;set;}
     public Resource ReportsTo{get;set;}
     public ICollection<Resource> Reporters{get;set;}
}

then the mapping as

        modelBuilder.Entity<Resource>().HasOptional(r => r.ReportsTo)
            .WithMany(r => r.Reporters)
            .HasForeignKey(r => r.ReportsToId);


You cannot have self referencing one-to-one relation because ResourceId is your PK. If you make it also FK you would say that dependent Resource is related to the principal resource with the same ResourceId but it cannot be because ResourceId must be unique. Self referencing one-to-one relation is not possible in EF at all because EF doesn't support unique non primary keys.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜