让我们假设我们有这个
class A
{
[Key]
public int Id { get; set; }
public string X { get; set; }
public string Y { get; set; }
public B B;
}
class B
{
[Key]
public int Id { get; set; }
public string X { get; set; }
public string Y { get; set; }
public virtual ICollection<A> As { get; set; }
}假设保证X和Y对在B中是唯一的,因此{X,Y}可以是B上的组合主键,但不是,Id是。
是否可以使用Fluent API通过这个假的外键关系来表示A.B应该是一个导航属性?
类似这样的东西,除了它不起作用:
HasRequired(a => a.B).WithMany(b => b.As).HasForeignKey(a => new { a.X, a.Y })发布于 2012-08-16 22:34:40
你说你想要“假的”外键,我不确定这是否意味着你不想让你的数据库反映这种关系。如果是这种情况,那么你不想用流利的语言来表达这一点,你应该在你的业务逻辑中强制这样做。如果您确实想要一个真正的外键,那么您需要更改B的主键,然后创建复合外键附件。您的初始A类中有一个拼写错误,您没有将导航属性B创建为一个属性。我假设这些不是您的真实对象,但我能够让它像这样工作:
public class A
{
public int Id { get; set; }
public string X { get; set; }
public string Y { get; set; }
public virtual B B { get; set; }
}
public class B
{
public int Id { get; set; }
public string X { get; set; }
public string Y { get; set; }
public virtual ICollection<A> As { get; set; }
}
public class Model : DbContext
{
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<B>()
.HasKey(b => new { b.Id, b.X, b.Y });
modelBuilder.Entity<A>()
.HasRequired(a => a.B)
.WithMany(b => b.As)
.HasForeignKey(a => new { a.Id, a.X, a.Y });
}
}https://stackoverflow.com/questions/11988914
复制相似问题