如何配置三个表之间的关系以获取所有相关数据?
我有以下模型(以及数据库中的相同表):
public class Client
{
public Guid ClientId { get; set; }
public string FirstName { get; set; }
public virtual ClientCard ClientCard { get; set; }
}
public class Card
{
public Guid CardId { get; set; }
public string Number { get; set; }
public virtual ClientCard ClientCard { get; set; }
}
public class ClientCard
{
public Guid ClientCardId { get; set; }
public Guid CardId { get; set; }
public Guid ClientId { get; set; }
public virtual Client Client { get; set; }
public virtual Card Card { get; set; }
}
以及以下 OnModelCreating 方法:
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Conventions.Remove<PluralizingTableNameConvention>();
...
builder.Entity<ClientCard>()
.HasKey(x => x.ClientCardId);
builder.Entity<ClientCard>()
.HasRequired(x => x.Client)
.WithRequiredPrincipal(x => x.ClientCard);
builder.Entity<ClientCard>()
.HasRequired(x => x.Card)
.WithRequiredPrincipal(x => x.ClientCard);
base.OnModelCreating(builder);
}
但是返回的结果没有相关数据。为什么?
最佳答案
对于您的代码,请尝试类似:
public class Client
{
public Guid ClientId { get; set; }
public string FirstName { get; set; }
public virtual ICollection<ClientCard> ClientCard { get; set; }
}
public class Card
{
public Guid CardId { get; set; }
public string Number { get; set; }
public virtual ICollection<ClientCard> ClientCard { get; set; }
}
public class ClientCard
{
public Guid ClientCardId { get; set; }
public Guid CardId { get; set; }
public Guid ClientId { get; set; }
public virtual Client Client { get; set; }
public virtual Card Card { get; set; }
}
和映射:
builder.Entity<Client>()
.HasKey(t => t.ClinetID);
....
builder.Entity<Client>()
.HasMany(a => a.ClientCard)
.WithRequired(p => p.Client)
.HasForeignKey(p => p.ClientID);
对于卡片
....
builder.Entity<Card>()
.HasMany(a => a.ClientCard)
.WithRequired(p => p.Card)
.HasForeignKey(p => p.CardID);
但我认为最好的方法是为每个实体创建一个单独的 map 文件
关于c# - Entity Framework Fluent API 映射问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929861/