Robert
Robert

Reputation: 2701

C# and EF cannot insert NULL to Id column

I have entity in C# that has Id column. This is Primary key. But I don't to have it as Identity column. I want to assign value to Id column in my code in C#. Entity:

    public class MasterReview
        {
            public int Id { get; set; }

In database I have column Id, Identity Specification is set as no. In C# when I add new entity I set value to Id:

    public void Add(int reviewId, string title, string language, string assignee)
            {
                using (var uow = unitOfWorkFactory.CreateUnitOfWork())
                {
                    uow.MasterReviewRepository.Add(new Models.MasterReview()
                    {
                        Id = reviewId,
                        Title = title,
                        Language = language,
                        Assignee = assignee
                    });

                    uow.Save();
                }
            }

And when I call uow.Save I get error:

Cannot insert the value NULL into column 'Id', table 'MyApp.dbo.MasterReview'; column does not allow nulls. INSERT fails.

Value is set, is not empty. It's 3.

enter image description here

Upvotes: 2

Views: 1494

Answers (1)

Roman Marusyk
Roman Marusyk

Reputation: 24619

Try to add DatabaseGeneratedOption.None annotation

public class MasterReview
{
   [DatabaseGenerated(DatabaseGeneratedOption.None)]
   public int Id { get; set; }
}

or if you use FluentAPI

modelBuilder.Entity<MasterReview>().Property(t => t.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

DatabaseGeneratedOption.None option specifies that the value of a property will not be generated by the underlying database. So, use it if you want to provide your own values to id properties instead of database generated values

But note: EF will throw an exception if you do not provide unique values each time when Id is a primary key property.

Upvotes: 4

Related Questions