c# - 首先将外键映射到 EF 代码中的非主代理键列

标签 c# entity-framework ef-code-first foreign-keys entity-framework-6

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 中

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

我明白这个错误,但我只想通过 Bid 指向 C 类,我如何在不干扰 A 和 B 之间的关系的情况下实现它。

最佳答案

此问题针对 EF6 进行了标记。但是,如果您在搜索 EF Core 时发现它。可以用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; }
}

关于c# - 首先将外键映射到 EF 代码中的非主代理键列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38029313/

相关文章:

c# - 使用 FromUri 将复杂对象传递给 ASP.NET Web API

database - Linq 到具有大数据库的实体

c# - EF LINQ ToList 非常慢

c# - Entity Framework 默认日期时间注释不迁移

c# - 如何修复 Mono 3.0.3、Entity Framework 6 Beta2 和 Npgsql 上 MVC3 项目的 DbProviderServices 继承错误?

entity-framework - 获取SQL以进行自动迁移的策略

mapping - Entity Framework 4.1 代码优先方法 : how to define length of properties

c# - 后退按钮专注于列表操作

c# - C# 中的 CTCP 原始协议(protocol) ACTION 命令

c# - 正则表达式捕获带有目标短语的句子