实体类型的属性是键的一部分,因此不能修改或标记为已修改
我使用Entity Framework 7.0.0-rc1-final和SQL 2014 LocalDB(代码优先)。 我有模特课:
public class UnitGroup { public int UnitGroupId { get; private set; } public string Name { get; set; } public ObservableCollection UnitSet { get; set; } public UnitGroup() { UnitSet = new ObservableCollection(); } }
我使用此委托进行流畅配置:
Action<EntityTypeBuilder> UnitGroupConfig = delegate (EntityTypeBuilder e) { e.Property(p => p.Name).IsVarchar(25).IsRequired(); e.HasAlternateKey(p => p.Name); };
IsVarchar()是我的扩展方法:
public static PropertyBuilder IsVarchar(this PropertyBuilder propertyBuilder, int maxLength) { return propertyBuilder.HasColumnType($"varchar({maxLength})"); }
然后我像这样使用它:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(e => UnitGroupConfig(e)); }
这是此表的迁移代码:
migrationBuilder.CreateTable( name: "UnitGroup", columns: table => new { UnitGroupId = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column(type: "varchar(25)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_UnitGroup", x => x.UnitGroupId); table.UniqueConstraint("AK_UnitGroup_Name", x => x.Name); });
迁移后,在我的Db: UnitGroup表中有一个表
我需要在我的Prism数据模块中封装EF。 我有一个课程:
public class DataService : IDataService { private DataContext context; public DataService() { context = new DataContext(); } public IQueryable GetAsTracking(params Expression<Func>[] includes) where T : class { return includes.Aggregate(context.Set().AsTracking(), (source, expression) => { if (expression.Body is MemberExpression) { return source.Include(expression); } return source; }); } public int SaveChanges() { return context.SaveChanges(); }
}
最后,我尝试运行这样的代码:
var ds = new DataService(); var ug = ds.GetAsTracking().First(); ug.Name="new value"; ds.SaveChanges();
并得到此错误:
实体类型“UnitGroup”上的属性“Name”是键的一部分,因此无法修改或标记为已修改。
我在这里发现了类似的问题。 这是一直在编辑主键的问题。 我检查了所有描述的部件两次。 属性名称不是主键的一部分,它是唯一键的一部分。 当我使用EF6时,我在部分迁移类中有代码:
CreateIndex("UnitGroup", "Name", unique: true);
它创建了相同的唯一键,我有能力编辑名称。 为什么现在在EF7中现在不可能?
由于Rowan Miller,我解决了这个问题。 他说:
在EF Core中,备用密钥被设计为用作关系的目标(即,将存在指向它的外键)。 目前EF不支持更改值。
如果我想要属性的唯一索引,那么我必须使用此代码:
modelBuilder.Entity().HasIndex(u => u.Name).IsUnique();