gpt4 book ai didi

mysql - 与 EF6、MySQL、MVC 错误的一对零/一关系

转载 作者:行者123 更新时间:2023-11-29 22:28:56 25 4
gpt4 key购买 nike

我已经设置了实体:

public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }

public string UserName { get; set; }
public string Password { get; set; }

public virtual Permissions Permissions { get; set; }
...
}
public class Permissions
{
[Key, ForeignKey("User")]
public Guid UserId { get; set; }

public virtual User User { get; set; }

public bool UserType1 { get; set; }
public bool UserType2 { get; set; }
...
}

目的是进行非常简单的设置,将权限分离到另一个表中。播种数据库时,我创建了一些具有正确设置的权限的用户(使用外部编辑器检查表,它们具有用户/权限条目的匹配键)。设置代码为:

public class EfDbInitializer : DropCreateDatabaseAlways<EfDbContext>
{
protected override void Seed(EfDbContext context)
{

// Add admin user

User admin = new User
{
UserName = "Admin",
Password = "pass",
FirstName = "Administrator",
LastName = "Web",
Permissions = new Permissions().SetAdminPermissions()
};
context.Users.Add(admin);

context.Users.Add(new User { UserName = "User1", Password = "pass", FirstName = "John", LastName = "Doe", CreatedBy = admin, Permissions = new Permissions().AddFullPermissions().AddInstructorPermissions() });
context.Users.Add(new User { UserName = "User2", Password = "pass", FirstName = "Jenny", LastName = "Doh", CreatedBy = admin, Permissions = new Permissions().AddFullPermissions().AddBasicPermissions() });
context.Users.Add(new User { UserName = "User3", Password = "pass", FirstName = "Sasha", LastName = "Grey", CreatedBy = admin, Permissions = new Permissions().AddBasicPermissions() });
context.Users.Add(new User { UserName = "User4", Password = "pass", FirstName = "Arnold", LastName = "Schwarzenegger", CreatedBy = admin, Permissions = new Permissions().AddInstructorPermissions() });
base.Seed(context);
}
}

但是,当尝试访问相应的实体时,我总是遇到异常。例如,直接在 Controller 中我有

  if (filter == "Type1")
return View(_repository.Users.Where(p => p.Permissions.UserType1));

运行相应的操作会出现异常

System.Data.Entity.Core.EntityCommandExecutionException was unhandled by user code

我尝试在数据库配置中禁用延迟评估(Configuration.LazyLoadingEnabled = false;)。然后异常更改为:

An exception of type 'System.NullReferenceException' occurred in Web.WebUI.dll but was not handled in user code

检查 lambda 中的“p”对象,我发现字段已成功设置(用户名、密码等),但权限字段为空。

我使用MySql.Data 6.9.6; MySql.Data.Entity 6.9.6; Entity Framework 6.1.3

最佳答案

尝试 _repository.Users.Include(u => u.Permissions).Where(p => p.Permissions.UserType1)

https://msdn.microsoft.com/en-us/data/jj574232.aspx

关于mysql - 与 EF6、MySQL、MVC 错误的一对零/一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com