8

我无法在表中插入记录

public class KPITable
{

    [Key]        
    public int Id { get; set; }
    public string Name { get; set; }
    public string Query { get; set; }
    public string TableName { get; set; }
}

public class KPITableMap : EntityTypeConfiguration<KPITable>
{
    public KPITableMap()
    {
        ToTable("EIS_KPI", AppUtility.EISMDBSchemaName);
        Property(t => t.Id).HasColumnName("KPI_ID");           
        Property(t => t.Name).HasColumnName("NAME").HasMaxLength(20);
        Property(t => t.Query).HasColumnName("QUERY").HasMaxLength(20);
        Property(t => t.TableName).HasColumnName("TABLE_NAME").HasMaxLength(20);

    }
}

当我尝试添加新实体时出现错误

为类型为“EISM.Database.Models.KPITable”的不可为空的成员“Id”返回了一个空的存储生成值

var newEntity = new KPITable();
newEntity.Id = 55;
                newEntity.Name = data.Name;
                newEntity.Query = data.Query;
                newEntity.TableName = data.TableName;
_dbContext.KPIs.Attach(newEntity);
                _dbContext.Entry(newEntity).State = EntityState.Added;
                _dbContext.SaveChanges();
4

2 回答 2

12

这解决了我的问题

[Key]     
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }

或者你可以删除这一行

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
于 2013-10-14T05:39:16.283 回答
0

这应该有效:

var newEntity = new KPITable();
newEntity.Id = 55;
                newEntity.Name = data.Name;
                newEntity.Query = data.Query;
                newEntity.TableName = data.TableName;
_dbContext.KPIs.AddObject(newEntity);
_dbContext.SaveChanges();

附加适用于现有实体(当它们分离时,或者当您要将其附加到另一个实体时)。

AddObject 用于新实体。

于 2013-10-11T11:48:41.760 回答