c# - Entity Framework Fluent API 映射问题

标签 c# entity-framework ef-fluent-api

如何配置三个表之间的关系以获取所有相关数据?

我有以下模型(以及数据库中的相同表):

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/

相关文章:

c# - 反序列化接口(interface)集合时,使用自定义转换器从以前的数据模型反序列化 JSON 失败

c# - 以不同的形式单击按钮时更改标签文本

entity-framework - EntityFramework 给出 IDisposable 错误

c# - Entity Framework : SELECT From Where ID NOT IN

.net-core - EF Core Fluent API 中的多对多关系

c# - 如何使用 RANK() SQl 函数?

c# - Windows 服务键盘记录器

c# - 如何使用 LINQ 选择器设置通用属性

c# - 防止在多对多表上按约定创建索引

c# - Entity Framework 代码优先 Fluent API