小编Emi*_*org的帖子

即使定义了其他主键,实体框架 6 也会创建 Id 列

我将 DataObject 定义为:

public class SensorType : EntityData
{
    //PKs
    public string CompanyId { get; set; }
    public string ServiceId { get; set; }

    public string Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并使用 fluent API 使 CompanyId 和 ServiceId 成为复合键:

modelBuilder.Entity<SensorType>()
            .HasKey(t => new { t.CompanyId, t.ServiceId });

//No autogeneration of PKs
modelBuilder.Entity<SensorType>().Property(t => t.ServiceId)
            .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
modelBuilder.Entity<SensorType>().Property(t => t.CompanyId)
            .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
Run Code Online (Sandbox Code Playgroud)

即使设置了主键,实体框架也会在我运行 Add-Migration 时创建一个名为 Id 的列:

CreateTable(
            "dbo.SensorTypes",
            c => new
                {
                    CompanyId = c.String(nullable: false, maxLength: 128),
                    ServiceId = c.String(nullable: …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework data-annotations entity-framework-6 ef-fluent-api

5
推荐指数
1
解决办法
1296
查看次数