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
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.
Try:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TierId { get; set; }