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/