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