简体   繁体   中英

Entity framework add new entity

I unable to insert a record in table

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

    }
}

I am getting error when i try to add new entity

A null store-generated value was returned for a non-nullable member 'Id' of type 'EISM.Database.Models.KPITable

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

this has resolved my problem

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

OR you can just remove this line

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

This should work:

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

Attach is for existing entities (when they are detached, or when you want to attach it to another entity).

AddObject is for new entities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM