【问题标题】:Entity Framework does not update an auto-increment field of a computed key in mySql实体框架不更新 mySql 中计算键的自动增量字段
【发布时间】:2013-09-19 21:32:06
【问题描述】:

我正在尝试使用实体框架保存实体,尽管 EF 没有更新自动增量字段

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
}

我从 mySql 分析了以下命令:

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

【问题讨论】:

    标签: mysql entity-framework ef-code-first


    【解决方案1】:

    我已经更改了映射命令的顺序并且它正在工作。我不知道 EF 映射命令会改变映射结果。

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

    最后它生成了正确的sql命令:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 2011-03-12
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多