如何配置三个表之间的关系以获取所有相关数据?
我有以下模型(以及数据库中的相同表格):
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);
}
但结果在没有相关数据的情况下返回。为什么呢?
答案 0 :(得分:0)
对于您的代码,请尝试以下内容:
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);
卡片
error-channel
但我认为最好的方法是为每个实体创建一个单独的地图文件
答案 1 :(得分:0)
现在我使用以下型号:
public class Client
{
public Guid ClientId { get; set; }
public string FirstName { get; set; }
public Guid? CardId { get; set; }
public virtual Card Card { get; set; }
}
public class Card
{
public Guid CardId { get; set; }
public string Number { get; set; }
//public virtual Client Client { get; set; }
}
以及以下OnModelCreating方法:
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Conventions.Remove<PluralizingTableNameConvention>();
...
builder.Entity<Client>()
.HasOptional(x => x.Card)
//.WithOptionalPrincipal(x=> x.Client)
//or
//.WithOptionalDependent(x=> x.Client)
;
base.OnModelCreating(builder);
}
所有客户返回相关数据(如果存在)。但是如果我想要使用Card对象获取相关数据并取消注释public virtual Client Client { get; set; }
和WithOptionalPrincipal / WithOptionalDependent,我总是会遇到这些SqlException:&#34;无效的列名称&#39; Client_ClientId&#39;&#34; (如果使用WithOptionalPrincipal)或&#34;无效的列名&#39; Card_CardId&#39;&#34; (如果使用WithOptionalDependent)
答案 2 :(得分:0)
我终于为我的案子找到了一个解决方案。
首先,我从Client类中删除了CardId。 其次,我改变了我的OnModelCreating方法:
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Conventions.Remove<PluralizingTableNameConvention>();
...
builder.Entity<Client>()
.HasOptional(x => x.Card)
.WithOptionalDependent(x => x.Client)
.Map(x => x.MapKey("CardId"))
.WillCascadeOnDelete(false);
builder.Entity<Card>()
.HasOptional(x => x.Client)
.WithOptionalPrincipal(x => x.Card)
.WillCascadeOnDelete(false);
base.OnModelCreating(builder);
}