Entity Framework does not update an auto-increment field of a computed key in mySql

倾然丶 夕夏残阳落幕 提交于 2020-01-13 07:07:10

问题


I'm trying to save an entity using entityframework, although the EF is not update the auto-increment field

public class Address
{
    public int Id { get; set; }
    public int DatacenterId { get; set; }
    public virtual Datacenter Datacenter { get; set; }
}

public class AddressMapping : EntityTypeConfiguration<Address>
{
    public AddressMapping()
    {
        this.HasKey(k => new { k.Id, k.DatacenterId });
        this.HasRequired(itr => itr.Datacenter)
            .WithMany()
            .HasForeignKey(fk => fk.DatacenterId);

        this.Property(p => p.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

using (var context = new MyContext())
{
    var address = new Address(); //Initialize and set all values. Include the FK
    context.Address.Add(address);
    context.SaveChanges();

    //address.Id is still 0
}

I profiled the following command from mySql:

INSERT INTO `address`(
    `Id`, 
    `DatacenterId`, 
)VALUES(
    0, 
    1, 
)

回答1:


I've changed the order of mapping commands and it is working. I didn't know the EF mapping commands could change the mapping result.

public class AddressMapping : EntityTypeConfiguration<Address>
{
    public AddressMapping()
    {
        this.Property(p => p.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        this.HasKey(k => new { k.Id, k.DatacenterId });

        this.HasRequired(itr => itr.Datacenter)
            .WithMany()
            .HasForeignKey(fk => fk.DatacenterId);
    }
}

And finally it generated the correct sql command:

INSERT INTO `address`(
    `DatacenterId`, 
)VALUES(
    1, 
);
SELECT
    `Id`
FROM 
    `address`
WHERE  
     row_count() > 0 AND `Id` = last_insert_id() AND `DatacenterId` = 1


来源:https://stackoverflow.com/questions/18905268/entity-framework-does-not-update-an-auto-increment-field-of-a-computed-key-in-my

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!