EF Core assigns negative sequence number to autoincrement int field

c# entity-framework-core sql-server

Question

When the Attach method on the context is called to attach an object to the context a negative sequence number is supposed to be temporarily assigned to the Identity property. In my case the value appears to be permanent resulting in an error when finally saving the object to database.

 public virtual void Insert(TEntity entity)
    {
        entity.ObjectState = ObjectState.Added;
        _dbSet.Attach(entity);
        _context.SyncObjectState<TEntity>(entity);
    }

 public class Tier:Entity
{
    public Tier()
    {

    }
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int TierID { get; set; }
    public string CountryID { get; set; }
    public string TierName { get; set; }
    public int TierNo { get; set; }

    public virtual ICollection<AdministrativeStructure> AdministrativeStructures { get; set; }

    public Country Country { get; set; }
}

I am using Entityframework core 1.1.0 with MSSQL Server 2016

1
0
1/6/2017 12:10:20 PM

Popular Answer

Lets see. If you create a class with properties like this and won't give it any Input, the Integer will have following Value:

0

Code:

class Program
{   
  static void Main(string[] args)
  {
      tmpClass testClass = new tmpClass();
      Debug.WriteLine(testClass.IntTest);


  }

  public class tmpClass
  {
      public int IntTest { get; set; }
  }
}

As you can see I didn't manipulate anything. The Value ist zero, 0, the default Value from a Int. You said you use TierID as Primary Key Value. Does your Table know how to handle this, like it will give it a ID or do you need to give it a ID? Maybe thats where the Error occurs. Wrong Primary Key.

In your case it seems the Database Generation doesn't seem to work right.

MSDN Documentation

Try:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TierId { get; set; }
2
1/6/2017 10:17:39 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow