首页 > 解决方案 > 如何在通用存储库中将所有实体框架主列重命名为 Id?

问题描述

以下资源显示了如何为通用存储库生成部分类映射。我们的模型没有 Id 列,它们总是被命名为 ProductId、CustomerId 等(知道通用存储库存在很多争议,但是经理告诉我们应用它)

该方法导致客户端评估,这在 EFCore 3 中很慢/不允许。

Net Core:为所有表自动代码生成创建通用存储库接口 Id 映射

public partial class Product: IEntity
{
    [NotMapped]
    public int Id { get => ProductId; set => ProductId= value; }
}

有没有人有自动生成的代码或 T4 来创建这个结果?想遍历所有脚手架模型并将类成员重命名为 id,将列重命名为 CustomerId、SalesId、ProductId 等?代码还需要根据需要更新模型构建器。EF Core 2 有这样的选项吗?

如何在实体框架-6的onmodelcreating方法中映射与模型不同的表名和列名?

它可以通过 Data Annotation 或 FluentAPI 完成,对任何选项开放。

public class Product
{
    [Column("ProductId")]
    public int Id { get; set; }

    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public float Cost { get; set; } 
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>()
        .Property(p => p.Id)
        .HasColumnName("ProductId");
}

标签: c#entity-frameworkasp.net-core.net-coret4

解决方案


推荐阅读