繁体   English   中英

EF Core 5.0 中的一对一关系

[英]One-to-One relationship in EF Core 5.0

我正在创建一个标准示例 model User -> UserProfile。

应用用户

public class ApplicationUser : IdentityUser
{
    public Profile UserProfile { get; set; }
}

轮廓

public class Profile
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ApplicationUserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
    public string AvatarUrl { get; set; }
    public List<Bage> Bages { get; set; } = new List<Bage>();
}

数据库上下文

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Profile> Profiles { get; set; }
    public DbSet<Bage> Bages { get; set; }
    
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
        //
    }
}

这就是我添加数据的方式:

ApplicationUser botva = new ApplicationUser
{
    UserName = "12313dsafdsd2",
    Email = "dasd@gmail.com",
    SecurityStamp = Guid.NewGuid().ToString()
};
_context.Users.Add(botva);

Profile BotvaProfile = new Profile { Name = "123 123", AvatarUrl = "123", ApplicationUser = botva };
_context.Profiles.Add(BotvaProfile);

Bage bage = new Bage { Name = "123", ImgUrl = "url/123" };
_context.Bages.Add(bage);

BotvaProfile.Bages.Add(bage);
_context.SaveChanges();

在数据库中正确创建的所有内容。 唯一的问题是主ApplicationUser class,由于某种原因,不包含对 Profile 的引用:

在此处输入图像描述

在此处输入图像描述

问题是什么?

我认为您需要反转您的课程

public class ApplicationUser : IdentityUser
    {
        public int ProfileId
        public Profile Profile { get; set; }
    }

public class Profile
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
        public string AvatarUrl { get; set; }
        public List<Bage> Bages { get; set; } = new List<Bage>();

    }

在这种情况下,您的代码将是


var botvaProfile = new Profile { Name = "123 123", AvatarUrl = "123"} 
var bage = new Bage { Name = "123", ImgUrl = "url/123" };
botvaProfile.Bages.Add(bage);

ApplicationUser botva = new ApplicationUser
            {
                UserName = "12313dsafdsd2",
                Email = "dasd@gmail.com",
                SecurityStamp = Guid.NewGuid().ToString(),
                Profile=botvaProfile
            };
 _context.Users.Add(botva);
 _context.SaveChanges();

暂无
暂无

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

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