[英]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.