【问题标题】:Null value for the foreign key relationship in Entity Framework实体框架中外键关系的空值
【发布时间】:2018-07-04 20:10:09
【问题描述】:

我正在创建一个简单的注册模块。我能够通过 SQL Management Studio 成功插入数据,但是当尝试运行应用程序时,它得到一个空值 ref。 UserxId 为 0,但配置设置为 Identity,我不确定为什么 AccessLevel 为空。代码非常简单,工作单元和通用存储库是标准的。

属性:

public class Userx
    {
        public int UserxId { get; set; }
        public int Access_Level_ID { get; set; }
        public virtual AccessLevel AccessLevel { get; set; }
        public string username { get; set; }
        public string password { get; set; }


    }

配置:

public class UserxConfig : EntityTypeConfiguration<Userx>
    {
        public UserxConfig()
        {
            ToTable("Userx");
            HasKey(x => new { x.UserxId, x.Access_Level_ID });

            Property(x => x.UserxId)
                .HasColumnName("UserxId")
                .HasColumnType(SqlDbType.Int.ToString())
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

            Property(x => x.Access_Level_ID)
             .HasColumnName("Access_Level_ID")
             .HasColumnType(SqlDbType.Int.ToString())
             .IsRequired();

            HasRequired(x => x.AccessLevel)
                .WithMany()
                .HasForeignKey(x => x.Access_Level_ID)
                .WillCascadeOnDelete(false);

        }
    }

下面是控制器的代码

[HttpPost]
        public ActionResult Registers(Userx userx)
        {

                if (ModelState.IsValid)
                {
                    using (var scope = new TransactionScope())
                    {
                        var encryptedPw = CustomEncrypt.Encrypt(userx.password);
                        var user = new Userx
                        {
                            Access_Level_ID = userx.Access_Level_ID,
                            username = userx.username,
                            password = userx.password
                        };
                        _unitOfWork.UserxRepository.Insert(user);
                        _unitOfWork.Save();
                        scope.Complete();
                    }
                }
                else
                {
                    ModelState.AddModelError("", "One or more fields have been");
                }

            return View();
        }

视图是自动生成的。

sample value while debugging, after the line, null value exception appears.

基本上我有两个问题,

  1. 为什么 UserxId 实际上应该是自动生成和自动递增的 0
  2. AccessLevel 应该有价值吗?我相信该属性用于映射外键。

更新: AccessLevel 的属性:

public class AccessLevel
    {
        public int Access_Level_ID { get; set; }
        [Required]
        public string Level { get; set; }
        [Required]
        public string Description { get; set; }
    }

配置:

public class AccessLevelConfig : EntityTypeConfiguration<AccessLevel>
    {
        public AccessLevelConfig()
        {
            ToTable("AccessLevel");
            HasKey(x => x.Access_Level_ID);

            Property(x => x.Access_Level_ID)
                .HasColumnName("Access_Level_ID")
                .HasColumnType(SqlDbType.Int.ToString())
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        }
    }

数据上下文:

public DbSet<AccessLevel> AccessLevel { get; set; }
        public DbSet<Userx> Userx { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new AccessLevelConfig());
            modelBuilder.Configurations.Add(new UserxConfig());
            base.OnModelCreating(modelBuilder);
        }

Null Value Reference Exception Screenshot

修复: UserxRepository 返回空值 ref。例外。

之前:

 private readonly UnitOfWork _unitOfWork;

       public AuthController(UnitOfWork unitOfWork;)
        {
            _unitOfWork = unitOfWork;
        }

之后:

private readonly UnitOfWork _unitOfWork;

       public AuthController()
        {
            _unitOfWork = new UnitOfWork;
        }

我在之前的代码中尝试完成的是通过在构造函数中包含 UnitOfWork 依赖类来创建抽象,以便预先实例化对象。

【问题讨论】:

  • 保存 IIRC 后分配实体的 ID。
  • 好的,AccessLevel 怎么样?我不认为它应该有一个值,但它抛出了一个空异常。你碰巧知道应该传递什么值吗?
  • Access_Level_ID 是一个外键,这意味着如果您将其设置为某个值,实体框架将检查是否存在具有此 ID 的 AccessLevel 实体(在提供的屏幕截图中为 2)。你的数据库中有这样的实体吗?如果是,请提供异常的详细信息(消息、类型),因为目前我似乎找不到其他解释
  • 嗨@JakubJankowski 我已经添加了更多细节。非常感谢您的帮助。
  • 对我来说似乎有值 null (userx) 传递给 Registers() 方法或 Userxrepository 为 null。

标签: c# asp.net asp.net-mvc entity-framework ef-code-first


【解决方案1】:

在 UserxId 上定义 Userx 表的主键。它会自动生成自增标识。

public class Userx
    {
        [Key] //TELL EF TO AUTOGENERATE ID
        public int UserxId { get; set; }
        public int? Access_Level_ID { get; set; } //MAKE ACCESS_LEVEL_ID NULLABLE
        public virtual AccessLevel AccessLevel { get; set; }
        public string username { get; set; }
        public string password { get; set; }
    }

【讨论】:

    【解决方案2】:
    public class Userx
        {
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //TELL EF TO AUTOGENERATE ID
            public int UserxId { get; set; }
            public int? Access_Level_ID { get; set; } //MAKE ACCESS_LEVEL_ID NULLABLE
            public virtual AccessLevel AccessLevel { get; set; }
            public string username { get; set; }
            public string password { get; set; }
        }
    

    【讨论】:

    • 这已在 DbConfiguration 上完成。 screenshot 2. 不同之处在于您只是使用了数据注释。尝试使 Access_Level_ID 可以为空,但遇到了同样的问题。
    猜你喜欢
    • 1970-01-01
    • 2017-07-20
    • 2020-07-08
    • 1970-01-01
    • 2018-09-09
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多