简体   繁体   中英

One-to-One relationship in EF Core 5.0

I am creating a standard example model User -> UserProfile.

ApplicationUser

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

Profile

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

DbContext

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

This is how I add data:

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

Everything created correctly in the database. The only problem is that the main ApplicationUser class, for some reason, does not contain a reference to Profile:

在此处输入图像描述

在此处输入图像描述

What is the problem?

I think you need to inverse your classes

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

    }

in this case your code will be


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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