Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The property on entity type is part of a key and so cannot be modified or marked as modified

I use Entity Framework 7.0.0-rc1-final with SQL 2014 LocalDB (code first). I have the model class:

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>();
    }
}

I use this delegate for fluent configuration:

Action<EntityTypeBuilder<UnitGroup>> UnitGroupConfig = delegate (EntityTypeBuilder<UnitGroup> e) {
        e.Property(p => p.Name).IsVarchar(25).IsRequired();

        e.HasAlternateKey(p => p.Name);
    };

IsVarchar() is my extension method:

public static PropertyBuilder IsVarchar(this PropertyBuilder<string> propertyBuilder, int maxLength) {
        return propertyBuilder.HasColumnType($"varchar({maxLength})");
    }

Then I use it like this:

protected override void OnModelCreating(ModelBuilder modelBuilder) {    
        modelBuilder.Entity<UnitGroup>(e => UnitGroupConfig(e));
}

This is migration code for this table:

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);
            });

After migration a have table in my Db:UnitGroup table

I need to encapsulate EF in my Prism Data Module. I have a class for this:

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();
}

}

Finally, I try to run code like this:

var ds = new DataService();
var ug = ds.GetAsTracking<UnitGroup>().First();
ug.Name="new value";
ds.SaveChanges();

and get this error:

The property 'Name' on entity type 'UnitGroup' is part of a key and so cannot be modified or marked as modified.

I have found similar questions here. It was a problem in editing primary key all the time. I checked all described parts twice. Property Name is not part of primary key, it's part of the unique key. When I have used EF6, I had code in partial class of migration:

CreateIndex("UnitGroup", "Name", unique: true);

which was created the same unique key and I had the ability to edit Name. Why now it's impossible now, in EF7?

like image 247
cyberVoOdOo Avatar asked Feb 10 '16 07:02

cyberVoOdOo


1 Answers

I solved the problem thanks to Rowan Miller. He said:

In EF Core, an alternate key is designed to be used as the target of a relationship (i.e. there will be a foreign key that points to it). Currently EF does not support changing the values.

If I want a unique index on the property, then I must use this code:

modelBuilder.Entity<UnitGroup>().HasIndex(u => u.Name).IsUnique();
like image 173
cyberVoOdOo Avatar answered Oct 11 '22 03:10

cyberVoOdOo