首先将外键映射到EF代码中的非主代理键列 [英] Mapping foreign key to non primary surrogate key column in EF code first

查看:268
本文介绍了首先将外键映射到EF代码中的非主代理键列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class A    
{   
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int Aid { get; set; }    

    public virtual ICollection<B> B { get; set; }    
}


public class B
{    
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     
    public virtual int Bid { get; set; }

    [Key]
    [Column(Order = 0)]
    [Required]           
    Public virtual string BName {get ; set}

    [Key]
    [Column(Order = 1)]
    [Required]      
    public virtual int Aid { get; set; }

    [ForeignKey("Aid")]
    public virtual  A A { get; set; }

    public virtual ICollection<C> C { get; set; }    
}


public class C
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     
    public virtual int Cid { get; set; }

    [Key]
    [Column(Order = 0)]
    [Required]    
    Public virtual string CName {get ; set}    

    [Key]
    [Column(Order = 1)]
    [Required]          
    public virtual int Bid { get; set; }

     [ForeignKey("Bid")]
     public virtual  B B { get; set; } 
}

B和C之间的关系困扰着我。我不想包括BName作为C类中的外键

relationship between B and C is troubling me .I dont want to include BName as foreign key in Class C


错误:在关系约束中,从属角色和主体角色
的属性数必须为相同

Error : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical

我理解错误,但是我只想通过Bid指向C类,如何在不干扰两者之间关系的情况下实现它A和B。

I understand the error but I want to point to C class only by Bid ,how I can achieve it without disturbing the relationship between A and B.

推荐答案

该问题被标记为EF6。但是,如果您找到此搜索EF Core。可以使用备用键

This question is tagged for EF6. But if you find this searching for EF Core. Can use Alternate Keys.

来自链接:


备用键可用作关系的目标。

Alternate keys can be used as the target of a relationship.



class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts)
            .HasForeignKey(p => p.BlogUrl)
            .HasPrincipalKey(b => b.Url);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public string BlogUrl { get; set; }
    public Blog Blog { get; set; }
}

这篇关于首先将外键映射到EF代码中的非主代理键列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆