在阅读了这篇关于向 UserProfile 表添加自定义数据的好BLOG之后,我想将其更改为 UserProfile 表应该存储默认数据的方式 + 另一个存储所有附加信息的类。
使用 Internet 应用程序模板创建新项目后,我创建了两个类:
学生.cs
[Table("Student")]
public class Student
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public virtual int StudentId { get; set; }
public virtual string Name { get; set; }
public virtual string Surname { get; set; }
public virtual int UserId { get; set; }
}
用户配置文件.cs
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual int StudentId { get; set; }
public virtual Student Student { get; set; }
}
另外,我已经从 AccountModel.cs 中删除了 UserProfile 定义。我的数据库上下文类如下所示:
MvcLoginDb.cs
public class MvcLoginDb : DbContext
{
public MvcLoginDb()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Student> Students { get; set; }
}
再次,我从 AccountModel.cs 中删除了 db 上下文定义。
在 Package-Manager-Console 里面我写过:
Enable-Migrations
我的 Configuration.cs 看起来像这样:
internal sealed class Configuration : DbMigrationsConfiguration<MvcLogin.Models.MvcLoginDb>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MvcLogin.Models.MvcLoginDb context)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
if (!WebSecurity.UserExists("banana"))
WebSecurity.CreateUserAndAccount(
"banana",
"password",
new
{
Student = new Student { Name = "Asdf", Surname = "Ggjk" }
});
}
}
这是将学生数据添加为创建新班级的想法,但这种方法不起作用,因为在运行Update-Database -Verbose后我收到错误: 从对象类型 MvcLogin.Models.Student 到已知托管的不存在映射提供者本机类型。
任何人都可以解释为什么我会收到这个错误,我应该使用不同的方法在不同的表中存储额外的数据吗?