用户和管理员是1对1的关系,其中1个用户只有1个管理员角色。
之前我通过在此链接Click here之后的管理员类的第一行添加[Key]来修复了ModelValidationException,但现在我收到了此错误:
无法确定之间关联的主要结束 类型' RecreationalServicesTicketingSystem.Models.Administrator'和 ' RecreationalServicesTicketingSystem.Models.User&#39 ;.主要目的 必须使用以下任一方式显式配置此关联 关系流畅的API或数据注释。
我尝试过这个解决方案,但它仍然给了我同样的错误。Click Here
User.cs
public class User
{
public int UserID { get; set; }
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
public string FirstMidName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public int DepotID { get; set; }
public int DepartmentID { get; set; }
public int TicketID { get; set; }
public string FullName
{
get { return LastName + ", " + FirstMidName; }
}
//Setting up relationships A use can apply for any number of tickets, so Tickets is defined as a collection of Ticket entities.
public virtual ICollection<Ticket> Tickets { get; set; }
//Setting up relationships Users can only have ONE adminstrator so we use public virtual Administrator Administrator { get; set; }
public virtual Administrator Administrator { get; set; }
public virtual Department Department { get; set; }
public virtual Depot Depot { get; set; }
}
Administrator.cs
public class Administrator
{
[Key]
public int AdminID { get; set; }
public int TicketID { get; set; }
public int UserID { get; set; }
[StringLength(50)]
public string AdminRole { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
public virtual User User { get; set; }
}
这是在我执行用户和管理员迁移的configuration.cs中。
用户
var users = new List<User>
{
new User { FirstMidName = "lala", LastName = "la",
EnrollmentDate = DateTime.Parse("2016-02-18") },
new User { FirstMidName = "baba", LastName = "baba",
EnrollmentDate = DateTime.Parse("2016-02-18") },
new User { FirstMidName = "dada", LastName = "dada",
EnrollmentDate = DateTime.Parse("2016-02-18") },
new User { FirstMidName = "Christine", LastName = "West",
EnrollmentDate = DateTime.Parse("2016-02-18") },
};
管理员
var administrator = new List<Administrator>
{
new Administrator {AdminID = 1, AdminRole = "Administrator LVL1", User = users.Single ( s => s.UserID == 1),
Tickets = new List<Ticket>() },
new Administrator {AdminID = 2, AdminRole = "Administrator LVL2", User = users.Single ( s => s.UserID == 2),
Tickets = new List<Ticket>() },
new Administrator {AdminID = 3, AdminRole = "Administrator LVL3", User = users.Single ( s => s.UserID == 3),
Tickets = new List<Ticket>() }
};
administrator.ForEach(s => context.Administrators.AddOrUpdate(p => p.AdminID, s));
context.SaveChanges();
}