Search code examples
c#sql-serverentity-framework-6newid

An ID number cannot be created in the database if it is auto generated by newid() InSqlserver with EF6


I created a column in a table named [Id] and made its type nvarchar(50), and its value is automatically by newid(), which is a mixture of letters and numbers, when adding a new record inside the database through a (sql server managment) , the new number does not appear until I execute the table.

The problem is not here, the real problem is when creating a new record from within EF6, the record cannot be added without specifying the identity value, and the following message appears:

The key field 'Id' cannot have a value of null. A non-null value is required for the key fields defined on type 'Booking'.

this code for sqlserver table


CREATE TABLE [dbo].[TableName](
    [id] [varchar](10) NOT NULL,
    [Price] [nvarchar](10) NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[TableName] ADD  DEFAULT (concat(left(newid(),(4)),'-',abs(checksum(newid()))%(10000))) FOR [id]
GO

In Ef6 Use Code

context Db = new context ();
t TableName = new TableName{
Price=10
};
db.TableName.add(t);
db.SaveChanges();

Solution

  • you must add this code on Migration Class(My DbMigration's name is Initial) before level add-migration

    this is code for only EF Classic

    , defaultValueSql: "concat(left(newid(),(4)),'-',abs(checksum(newid()))%(10000))"
    
    

    My class DbMigration

    
    using System.Data.Entity.Migrations;
      
      public partial class Initial : DbMigration
      {
          public override void Up()
          {  CreateTable(
                  "dbo.TableNames",
                  c => new
                      {  Id = c.String(nullable: false, maxLength: 100, defaultValueSql: "concat(left(newid(),(4)),'-',abs(checksum(newid()))%(10000))"),
                          Price = c.String(maxLength: 100),
                      })  .PrimaryKey(t => t.Id);
                }
          
          public override void Down()
          {  DropTable("dbo.TableNames"); }
      }
    

    my class :

    public class TableName
    { 
        [Key]
        [MaxLength(100)]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public string Id { get; set; }
    
        [MaxLength(100)]
        public string Price { set; get; }
    }
    

    my DbContext:

    public class MyContext : DbContext
    {
        public MyContext()
            : base("Name=ConnectionString")
        { }
        public DbSet<TableName> TableName { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {   base.OnModelCreating(modelBuilder); }
     }
    

    add TableName

    var Db = new MyContext();
    var TableName = new TableName{ Price = "40"};
    Db.TableName.Add(TableName);
    Db.SaveChanges();
    

    my Package:

    • EntityFramework:6.4.4