richardwiden
richardwiden

Reputation: 1602

Why does a newly created EF-entity throw an ID is null exception when trying to save?

I´m trying out entity framework included in VS2010 but ´ve hit a problem with my database/model generated from the graphical interface.

When I do:

user = dataset.UserSet.CreateObject();
user.Id = Guid.NewGuid();
dataset.UserSet.AddObject(user);
dataset.SaveChanges();

{"Cannot insert the value NULL into column 'Id', table 'BarSoc2.dbo.UserSet'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

The table i´m inserting into looks like so:

-- 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 in the wrong way or doing something else basic wrong?

Upvotes: 2

Views: 3215

Answers (2)

user175832
user175832

Reputation:

You shouldn't have to set the ID property manually. It should be set automatically when you save. I assume you are using the standard template for Entity Framework, and not the Self-tracking entities template or POCOs template. If so, something along the following lines would seem more appropriate:

User user = new User();
dataset.AddToUsers(user);
dataset.SaveChanges();

Upvotes: 3

varun sharma
varun sharma

Reputation: 81

On the model for the fields which is defined as key, add the following attribute. This key which is not marked as IDENTITY in database, Entity Framework give the exception

[Key]
[Display(Name = "Id")]     
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
public int Id { get; set; }

Upvotes: 8

Related Questions