如何在我自己的类中定义外键。

Hui Liu-MSFT 40,266 信誉分 Microsoft 供应商
2024-04-24T07:56:48.63+00:00

嗨,伙计们,

我不确定这是否是问我问题的正确地方,但它在某种程度上与EF Core和Identity有关。

我在我的项目中使用 ASP.NET 核心标识。我已经添加了自己的自定义表以及 Microsoft Identity 自动创建的表,例如 (ASPNetUsers、ASPNETRoles)等。

现在我的问题是,我想使用 ASPNetUsers 的主键,例如我自己的表中的 Id 作为外键

谁能告诉我如何在我自己的班级中将其定义为外键。

这是我的代码示例:

public partial class FileUserInfo
    {
        public FileUserInfo()
        {
            FileUserInfoDetails = new HashSet<FileUserInfoDetails>();

        }

        public int FileUserInfoId { get; set; }
        public string UserName { get; set; }
        public string RecipientEmailAddress { get; set; }

        // This is my foreign key.
        public string CreatedByEmployeeId { get; set; }

        public DateTime CreationDate { get; set; }

        // How to define this here?   as  the class is not created by Microsoft Identity by default.
        //public virtual AspNetUsers CreatedByEmployee { get; set; }

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

出于这个原因,我不愿意创建单独的dbcontext(脚手架)。

Note:此问题总结整理于:How to define foriegn key in my own classes.

Entity Framework Core
Entity Framework Core
实体框架数据访问技术的轻量型、可扩展、开源、跨平台版本。
38 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Jiale Xue - MSFT 33,686 信誉分 Microsoft 供应商
    2024-04-24T09:18:10.6966667+00:00
     // How to define this here?   as  the class is not created by Microsoft Identity by default.  
     //public virtual AspNetUsers CreatedByEmployee { get; set; }  
    

    在 Asp.net Core Identity 中,该类映射到表,因此如果要配置外键,可以使用 IdentityUser 类,请检查以下代码:IdentityUserAspNetUsers

    public class FileUserInfo  
    {    
        [Key]  
        public int FileUserInfoId { get; set; }  
        public string UserName { get; set; }  
        public string RecipientEmailAddress { get; set; }  
    
        public DateTime CreationDate { get; set; }  
    
         // This is my foreign key. // use the ForieignKey attribute to assign the foreign key.  
        [ForeignKey("CreatedByEmployee")]  
        public string CreatedByEmployeeId { get; set; }  
        public virtual IdentityUser CreatedByEmployee { get; set; }  
    }  
    

    在 DbContext 中添加 FileUserInfos

    public class ApplicationDbContext : IdentityDbContext  
    {  
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)  
            : base(options)  
        {  
        }   
        public DbSet<FileUserInfo> FileUserInfos { get; set; }  
    }  
    

    迁移后,结果如下:

    139402-image.png

    有关使用 Asp.net Core Identity 的更多详细信息,请参阅 ASP.NET Core 上的 Identity 简介ASP.NET Core 中的 Identity 模型自定义

    由于该类继承了 ,在 Controller 中,可以注入 ,然后通过 访问表,然后就可以根据用户名找到当前用户,之后就可以得到用户 Id 值了。请参阅以下代码:ApplicationDbContextIdentityDbContextApplicationDbContextAspNetUserscontext.Users

    public class HomeController : Controller  
    {  
        private readonly ILogger<HomeController> _logger;  
        private readonly ApplicationDbContext _context;  
    
        public HomeController(ILogger<HomeController> logger, ApplicationDbContext applicationDbContext)  
        {  
            _logger = logger;  
            _context = applicationDbContext;  
        }  
    
        public IActionResult Index()  
        {  
            if (!string.IsNullOrEmpty(HttpContext.User.Identity.Name))  
            {  
                var user = _context.Users.Where(c => c.UserName == HttpContext.User.Identity.Name).FirstOrDefault();  
    
               //after getting the user, you can get the userid.  
                var userid = user.Id;  
                //or  
                var id = User.FindFirstValue(ClaimTypes.NameIdentifier);  
    
                var fileuser = new FileUserInfo() { CreatedByEmployee = user, UserName = "AA" };  
                _context.FileUserInfos.Add(fileuser);  
                _context.SaveChanges();  
    
                var result = _context.FileUserInfos.ToList();  
            }  
     
            return View();  
        }
    

    如果答案有帮助,请点击“接受答案”并点赞。

    注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助