c# – 即使定义了其他主键,Entity Framework 6也会创建Id列
发布时间:2020-12-15 22:35:37 所属栏目:百科 来源:网络整理
导读:我将DataObject定义为: public class SensorType : EntityData{ //PKs public string CompanyId { get; set; } public string ServiceId { get; set; } public string Type { get; set; }} 并使用流畅的API使CompanyId和ServiceId成为一个复合键: modelBui
我将DataObject定义为:
public class SensorType : EntityData { //PKs public string CompanyId { get; set; } public string ServiceId { get; set; } public string Type { get; set; } } 并使用流畅的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); 即使已设置主键,当我运行Add-Migration时,Entity Framework会创建一个名为Id的列: CreateTable( "dbo.SensorTypes",c => new { CompanyId = c.String(nullable: false,maxLength: 128),ServiceId = c.String(nullable: false,Type = c.String(),Id = c.String( annotations: new Dictionary<string,AnnotationValues> { { "ServiceTableColumn",new AnnotationValues(oldValue: null,newValue: "Id") ... }) .PrimaryKey(t => new { t.CompanyId,t.ServiceId }) .Index(t => t.CreatedAt,clustered: true); } 如何阻止EF添加此列? 解决方法
我怀疑它与您从EntityData派生类的事实有关,而EntityData有一个名为Id的属性.我的猜测是EF很混乱,因为有一个属性符合它的关键命名约定(即Id)和明确定义的键.
我怀疑你必须告诉它明确忽略Id. MSDN: EntityData Class 更新: 我假设您正在与Azure合作.这个SO question在答案中有一些额外的信息,可以帮助您找到最佳解决方案. 但是,我同意@Basic对你的问题的评论.由于它们引入的复杂性(和其他问题),我通常回避使用EF的复合键.我怀疑您的CompanyId和ServiceId字段的唯一约束将实现您想要的,而不会将它们包含在SensorType的主键中.这也意味着您可以只使用派生的Id属性作为主键,并避免整个问题.我不知道你的实现是否可行,但需要考虑. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |