问题
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