.NET Entity Framework Core 一对多关系

问题描述

当我尝试使用 EF 创建表时,我发现 User 表中的 FK 名称与我的预期不同,并且还为“允许为空”。我打算在“用户”表下创建 FK“orgId”。我提到了 website 这个。在示例中,它在“Student”表下方为“Grade”创建了一个外键。你能告诉我我在这里错过了什么吗? (*我使用 EntityFrameworkCore@3.1.0)

enter image description here

.mission {
  flex-direction: column;
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Domain
{
    public class User
    {
        [Key]
        public int userId { get; set; }
        [required]
        public string userEmail { get; set; }
        public string prevIoUsPW { get; set; }
        public string userHashedPassword { get; set; }
        public DateTime userResetPWDate { get; set; }
        public string userResetCode { get; set; }
        public string userFullName { get; set; }
        public string userOrgName { get; set; }
        public string userJobTitle { get; set; }
        public string userFName { get; set; }
        public string userLName { get; set; }
        public string userPhone { get; set; }
        public string userFax { get; set; }
        public string userLevel { get; set; }
        public DateTime userCreatedDate { get; set; }
        public DateTime userAccessedDate { get; set; }
        public string userComment { get; set; }

        public int orgId { get; set; }
        public virtual Organization Organization { get; set; }

        public virtual ICollection<PermissionPkgView> PermissionPkgView { get; set; }
    }
}

作为一些评论,我尝试按照方式,与参考相同。

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Domain
{
    public class Organization
    {
        [Key]
        public int orgId { get; set; }
        public string orgName { get; set; }
        public virtual ICollection<User> User { get; set; }
    }
}

然而,结果与样本不同。它创建了“FK_Student_Grade_GradeID”并允许为空。

enter image description here

解决方法

最后,我只使用了'Fluent API',然后它正常显示FK。 enter image description here

using Microsoft.EntityFrameworkCore;
using Domain;

namespace Persistence
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions options) : base(options)
        {
        }

        public DbSet<tbl_PW> tbl_PW { get; set; }
        public DbSet<User> User { get; set; }
        public DbSet<Organization> Organization { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<User>()
            .HasOne<Organization>(u => u.Organization)
            .WithMany(o => o.User)
            .HasForeignKey(u => u.orgId);
        }
    }
}