实体框架为连接表

时间:2017-02-27 07:30:19

标签: c# sql-server entity-framework

我试图在我的datacontext中为连接表(为m2m关系创建的那个)创建POCO实体。

我这样做的原因是我想要自己处理在表中插入的键。 (不要问我为什么,有几个性能问题。)

所以算法是这样的:

  1. 我使用基于现有表的原生ADO.NET工具生成POCO类,让我们说TableAnotherTable(此表加入另外两个Table和{{1} })。或者只是手动创建它。

  2. 我正在尝试为其添加迁移。使用AnotherTable或不使用-IgnoreChanges。如果没有-IgnoreChanges,则会尝试将现有表格TableAnotherTable重命名为TableAnotherTable1。这听起来很公平,但为什么呢?它应该只将现有表映射到新创建的POCO类。

  3. 我正在清理Up()Down()方法。

  4. 尝试运行应用并在上下文中执行一些CUD操作并不断收到错误:无效的对象名称dbo.TableAnotherTable1

  5. 所以主要问题:如何将实体框架创建的连接表映射到我自己的类,以便像使用常规实体一样使用它?

    更新

    public class Client
    {
      public int Id {get;set;}
      public ICollection<Group> Groups {get;set;}
    }
    
    public class Group
    {
      public int Id {get;set;}
      public ICollection<Client> Clients {get;set;}
    }
    

    没有其他配置或其他内容。

    数据库中的连接表名称为GroupClient

    使用ADO.NET poco生成工具检索的poco类是:

    [Table("GroupClient")]
    public partial class GroupClient
    {
        [Key]
        [Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Group_Id { get; set; }
    
        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Client_Id { get; set; }
    }
    

1 个答案:

答案 0 :(得分:1)

带有自动链接表的初始模型应该生成GroupClient表,其中两列Group_IdClient_Id形成PK。

您应该能够将其映射到显示生成的显式GroupClient实体的模型,该实体已经定义了属性和PK,但您需要更改现有实体导航属性的类型并指定FK&#39;:

public class Client
{
    public int Id { get; set; }
    [ForeignKey("Client_Id")]
    public ICollection<GroupClient> Groups { get; set; }
}

public class Group
{
    public int Id { get; set; }
    [ForeignKey("Group_Id")]
    public ICollection<GroupClient> Clients { get; set; }
}

我个人觉得使用Fluent配置更容易理解:

型号:

public class Client
{
    public int Id { get; set; }
    public ICollection<GroupClient> Groups { get; set; }
}

public class Group
{
    public int Id { get; set; }
    public ICollection<GroupClient> Clients { get; set; }
}

public class GroupClient
{
    public int Group_Id { get; set; }
    public int Client_Id { get; set; }
}

配置:

modelBuilder.Entity<GroupClient>()
    .ToTable("GroupClient")
    .HasKey(e => new { e.Group_Id, e.Client_Id });

modelBuilder.Entity<Group>()
    .HasMany(e => e.Clients)
    .WithRequired() // or (e => e.Group) in case you add nav property
    .HasForeignKey(e => e.Group_Id);

modelBuilder.Entity<Client>()
    .HasMany(e => e.Groups)
    .WithRequired() // or (e => e.Client) in case you add nav property
    .HasForeignKey(e => e.Client_Id);
相关问题