我最近出现了这个错误,我不知道我错了什么
错误:System.InvalidOperationException:'实体类型为Customer 不属于当前背景模型的一部分。'
当我运行代码
时,错误出现在列表(客户)中模型连接到具有客户表
的SQL数据库需要帮助的原因我不能继续使用该程序。致谢
主程序
static StoreSalesHandlingNewEntities1 db = new StoreSalesHandlingNewEntities1();
public static string ShowMenu()
{
Console.Clear();
List<Customer> customerList = db.Customer.ToList();
foreach (Customer c in customerList)
{
Console.WriteLine(c.ToString());
}
Console.WriteLine();
Console.WriteLine("1.. Login");
Console.WriteLine("2.. Register");
Console.WriteLine("3.. Exit");
return Console.ReadLine();
}
上下文
public partial class StoreSalesHandlingNewEntities1 : DbContext
{
public StoreSalesHandlingNewEntities1()
: base("name=StoreSalesHandlingNewEntities1 ")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Customer> Customer { get; set; }
public virtual DbSet<Employee> Employee { get; set; }
public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<Order> Order { get; set; }
}
客户
public partial class Customer
{
public string Name { get; set; }
public string Surname { get; set; }
public string IDNumber { get; set; }
public string EmailAddress { get; set; }
public string HomeAddress { get; set; }
public int MobileNumber { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public override string ToString()
{
return string.Format("Name: {0}, Surname: {1}, ID Number: {2}, Email: {3}, Address: {4}, Mobile: {5}, Username: {6}, Password: {7}",
Name, Surname, IDNumber, EmailAddress, HomeAddress, MobileNumber, Username, Password);
}
}
答案 0 :(得分:0)
如果您的表未在启动时创建,这就是原因。您需要在OnModelCreating方法覆盖中告诉DbContext它们。
您可以在此处执行自定义按实体映射,也可以将它们分离为单独的EntityTypeConfiguration类。
将它放在自定义DbContext类中:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().ToTable("Customer");
}