简体   繁体   English

实体框架中外键关系的空值

[英]Null value for the foreign key relationship in Entity Framework

I am creating a simple register module. 我正在创建一个简单的注册模块。 I was able to successfully insert data via SQL Management studio but when tried to run the application, it is getting a null value ref. 我能够通过SQL Management Studio成功插入数据,但是当尝试运行该应用程序时,它获取的是空值ref。 UserxId is 0 but the configuration is set to Identity and i'm not sure why AccessLevel is null. UserxId为0,但配置设置为Identity,我不确定为什么AccessLevel为null。 The code is very straightforward and unitofwork and generic repository is standard. 该代码非常简单,工作单元和通用存储库是标准的。

Property: 属性:

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; }


    }

Configuration: 组态:

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);

        }
    }

Below is the code for the controller 以下是控制器的代码

[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();
        }

The view is auto generated. 视图是自动生成的。

sample value while debugging, after the line, null value exception appears. 调试时输入样本值,在该行之后,出现空值异常。

Basically I have two questions, 基本上我有两个问题,

  1. Why was the UserxId 0 when in fact it should be auto generated and auto incremented 为什么实际上应该自动生成并自动递增UserxId 0
  2. Should the AccessLevel have value? AccessLevel应该有价值吗? I believe that property is used to map the foreign key. 我相信该属性用于映射外键。

Update: Property for AccessLevel: 更新:AccessLevel的属性:

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

Configuration: 组态:

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);
        }
    }

DataContext: DataContext:

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 空值参考异常屏幕截图

FIX: The UserxRepository was returning the null value ref. FIX: UserxRepository返回空值引用。 exception. 例外。

Before: 之前:

 private readonly UnitOfWork _unitOfWork;

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

After: 后:

private readonly UnitOfWork _unitOfWork;

       public AuthController()
        {
            _unitOfWork = new UnitOfWork;
        }

What i was trying to accomplish on the before code was to create an abstraction by having UnitOfWork dependency class in the constructor so the object will be pre-instantiated. 我试图在之前的代码上完成的工作是通过在构造函数中具有UnitOfWork依赖项类来创建一个抽象,以便该对象将被预先实例化。

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; }
    }

Define Primary Key to Userx table on UserxId. 在UserxId上定义Userx表的主键。 It will automatically generate auto increment identity. 它将自动生成自动增量标识。

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; }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM