1

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, 
)
4

1 回答 1

2

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
于 2013-09-20T13:06:44.860 回答