【问题标题】:Primary keys created by Entity Framework are not auto-incrementing实体框架创建的主键不是自动递增的
【发布时间】:2014-04-05 20:38:38
【问题描述】:

让我显示错误:

无法将值 NULL 插入到表的“Id”列中 'TCCDatabase.dbo.ProfessionalModels';列不允许空值。 插入失败。

尝试使用我的 EF 应用程序创建的数据库将 n 记录插入我的数据库时出现此错误。

我认为这是因为我的数据库 ID 列不是自动递增的。

我的问题是:为什么我的 Id 列不自动递增?

我的一个模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace TCCApplication.Models
{
    public class ProfessionalModel
    {
        public int Id { get; set; }

        public string Name { get; set; }

        [Column(TypeName = "DateTime2")]
        public DateTime BirthDate { get; set; }
        public int PhoneNumber { get; set; }
        public string Profession { get; set; }

        public UserAddressModel UserAddressModel { get; set; }
        public UserAccountModel UserAccountModel { get; set; }

        public ProfessionalModel() { }
    }
}

我的上下文类:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
using TCCApplication.Models;

namespace TCCApplication.EntityFramework
{
    public class TCCDatabase : DbContext
    {
        public DbSet<UserAccountModel> UserAccountContext { get; set; }
        public DbSet<ProfessionalModel> ProfessionalContext { get; set; }
        public DbSet<UserAddressModel> UserAddressContext { get; set; }

        public TCCDatabase()
        {}

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ProfessionalModel>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            modelBuilder.Entity<UserAccountModel>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            modelBuilder.Entity<UserAddressModel>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        }

    }
}

【问题讨论】:

  • 即使没有流畅的配置,您的 pk 的定义也应将身份规范设置为 yes 和 autoinc。如果您删除 fluent 配置并构建新的迁移会发生什么?
  • @user3411327 它创建一个空迁移
  • 必须在创建表时设置身份。如果这没有发生,那么稍后会解释如何引入它here

标签: c# .net entity-framework migration entity-framework-migrations


【解决方案1】:

基于this 问题,自动增加ID 似乎不是EF 的工作,而是数据库的工作。应该增加的列需要设置为标识。

【讨论】:

    猜你喜欢
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多