Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot insert the value NULL into column 'Id', Entity framework

I have the following model:

Services.StradaDataReview2Model.UOSChangeLog:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public int Accident_nr { get; set; }

public int Refnr { get; set; }

public int Action { get; set; }

public string Old_data { get; set; }

public string New_data { get; set; }

public DateTime SearchedFromDate { get; set; }

public DateTime SearchedToDate { get; set; }

public DateTime Changed { get; set; }

public string Username { get; set; }

public string Comment { get; set; }

Contracts.DataContracts.UOSChangeLog

public class UOSChangeLog
{
    public int Id { get; set; }
    public int Accident_nr { get; set; }
    public int Refnr { get; set; }
    public int Action { get; set; }
    public string Old_data { get; set; }
    public string New_data { get; set; }
    public DateTime SearchedFromDate { get; set; }
    public DateTime SearchedToDate { get; set; }
    public DateTime Changed { get; set; }
    public string Username { get; set; }
    public string Comment { get; set; }
}

Here Is how I Insert:

internal static bool SaveUOSChangeLog(List<Contracts.DataContracts.UOSChangeLog> values, string user)
{
    try
    {
        using (var ctx = new StradaDataReviewContext2())
        {
            var newVal = Mapper.Map<List<Contracts.DataContracts.UOSChangeLog>, List<Services.StradaDataReview2Model.UOSChangeLog>>(values);
            foreach(var val in newVal)
            {
                val.Username = user;
                val.Changed = DateTime.Now;
                ctx.UOSChangeLog.Add(val);
            }

            ctx.SaveChanges();
            return true;
        }
    }
}

When I run the code, I get the following error:

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

How can I make an auto increment of the Id column?

like image 875
Bryan Avatar asked Apr 10 '26 15:04

Bryan


1 Answers

I guess you are using Code First, which by convention will set the Id property as the primary key in the corresponding table that by default will have been defined as 'Identity'. I think that it is not necessary to set the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute. I would check first the database to see if in the corresponding table the Id column has been created as an Identity column. Also are you defining anything using Fluent API?

like image 165
V. Oikonomakos Avatar answered Apr 12 '26 05:04

V. Oikonomakos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!