I created a table in SQL Server Management Studio with two columns, FacilityId
is the primary key and not null. After the design, I manually added the first row.
However when I insert the new record into the table programmatically in C# code I get this error:
Cannot insert the value NULL into column 'FacilityId', table 'xxxxxxxx'; column does not allow nulls.
My table in code:
public class MyURL
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Column("FacilityId")]
public int FacilityId { get; set; }
[Column("Url")]
public string Url { get; set; }
}
To add new record by the below code:
public void AddNewUrl(int id, string url)
{
using (MyUrlContext context = new MyUrlContext())
{
context.Database.Connection.ConnectionString = GetConnectionString(context);
var data = GetNewUrl(id, url);
SaveContextAfterAddingNewRecord(context, data);
}
}
public virtual void SaveContextAfterAddingNewRecord(MyUrlContext context, MyURL data)
{
context.MyEndpoints.Add(data);
context.SaveChanges();
}
And
public class MyUrlContext : DbContext
{
public MyUrlContext():base()
{
Database.SetInitializer<MyUrlContext>(null);
}
public DbSet<MyURL> MyEndpoints { get; set; }
}
So what is wrong?
EDIT:
The db/table structure.
Also, I do have the value provided.
See the image:
I am sure that the identity property is off.
EDIT2:
The SS profiler indicated
exec sp_executesql N'INSERT [dbo].[TableName]([Url])
VALUES (@0)
SELECT [FacilityID]
FROM [dbo].[TableName]
WHERE @@ROWCOUNT > 0 AND [FacilityID] = scope_identity()',N'@0 nvarchar(max) ',@0=N'sdfsdf'