Why is a newly created EF object throwing an id is an exception when trying to save?
I am trying to implement the entity framework included in VS2010 but ran into a problem with my database / model generated from the GUI.
When I do this:
user = dataset.UserSet.CreateObject(); user.Id = Guid.NewGuid(); dataset.UserSet.AddObject(user); dataset.SaveChanges();
{"Cannot insert NULL value in column" Identity ", table" BarSoc2.dbo.UserSet ", column does not allow null values. INSERT does not work. \ R \ nApplication completed." }
The insert of the table you are entering looks like this:
-- Creating table 'UserSet'
CREATE TABLE [dbo].[UserSet] (
[Id] uniqueidentifier NOT NULL,
[Name] nvarchar(max) NOT NULL,
[Username] nvarchar(max) NOT NULL,
[Password] nvarchar(max) NOT NULL
);
GO
-- Creating primary key on [Id] in table 'UserSet'
ALTER TABLE [dbo].[UserSet]
ADD CONSTRAINT [PK_UserSet]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
Am I creating the object differently or am I doing something else wrong?
a source to share
You don't need to set the ID property manually. It should be installed automatically on save. I am assuming you are using the default template for the Entity Framework, not the Self-tracking entity template or the POCOs template. If so, then something along the following lines would seem more appropriate:
User user = new User();
dataset.AddToUsers(user);
dataset.SaveChanges();
In the model, for fields that are defined as key, add the following attribute. This key, which is not marked as IDENTITY in the database, Entity Framework throws an exception
[Key]
[Display(Name = "Id")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
public int Id { get; set; }
a source to share