Cannot insert the value NULL into column 'ID&#

2019-08-01 15:14发布

问题:

I am getting the exception "Cannot insert the value NULL into column 'ID'" when using Linq to Sql , I am leaving the ID property blank , but I have set my ID to auto-generate in my DBML file. This will work fine when I insert without an ID and let sql auto generate for me not using linq. The problem is LINQ is throwing an exception because it sees that ID is empty , even though if LINQ would just let it go through SQL is ok with it.

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL", IsPrimaryKey=true, IsDbGenerated=true)]
    public int ID
    {
        get
        {
            return this._ID;
        }
        set
        {
            if ((this._ID != value))
            {
                this.OnIDChanging(value);
                this.SendPropertyChanging();
                this._ID = value;
                this.SendPropertyChanged("ID");
                this.OnIDChanged();
            }
        }
    }

回答1:

You need to include 'IDENTITY' in your column definition:

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int ID
{ ... }

If that wont fix it try adding UpdateCheck=UpdateCheck.Never as well.



回答2:

I had a similar problem, caused by a missing key in my mapping configurations (I only had one key, and not a composite, as it should have been).

Thought I'd share the answer, since my problem was similar, but my solution is a little different.

In short, my context class and configurations look like this:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Loads the configuration:
        modelBuilder.Configurations.Add(new MyMyDataClassConfiguration()); 
    }

    // ...
}


public class MyDataClassConfiguration : EntityTypeConfiguration<MyDataClass>
{
    public MyDataClassConfiguration()
    {
        ToTable("MyDataTableName"); // Maps to table

        // Specify composite key (I was missing a key here)
        HasKey(data => new {data.First_Key_Name, data.Second_Key_Name });
    }
}