代码优先实体框架不允许访问表

本文关键字:不允许 访问表 框架 实体 代码 | 更新日期: 2023-09-27 18:35:37

我正在尝试首先使用代码为 asp.net mvc 应用程序生成数据库。 OrderItem 类确实在数据库中生成为 OrderItems 表,但我最终无法访问它。 我该怎么做才能允许以下内容,例如:db.OrderItems.Find(id);

模型如下:

namespace CustomerOrders.Models{
public class Customer
{
    public virtual int  CustomerID { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Company { get; set; }
    public virtual string Email { get; set; }
    public virtual string EmailCheck { get; set; }
}
public class Order
{
    public virtual int OrderID { get; set; }
    public virtual int CustomerID { get; set; }
    public virtual DateTime OrderDate { get; set; }
    public virtual double OrderTotal { get; set; }
    public virtual double Tax { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual List<OrderItem> OrderItems { get; set; }
}
public class OrderItem
{
    public virtual int OrderItemID { get; set; }
    public virtual int OrderID { get; set; }
    public virtual int ProductID { get; set; }
    public virtual double PricePerItem { get; set; }
    public virtual double Quantity { get; set; }
    public virtual Product Product { get; set; }
    public Order Order { get; set; }
}
public class Product
{
    public virtual int ProductID { get; set; }
    public virtual string Title { get; set; }
    public virtual string Description { get; set; }
    public virtual double Price { get; set; }
}
}

代码优先实体框架不允许访问表

你可能没有在你的 dbContext 中得到声明,所以打开 dbContext 并添加以下内容: public DbSet<OrderItem> OrderItems { get; set; }

你应该得到这个:

public class CustomerOrdersDB : DbContext
{
    public DbSet<Order> Orders { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<OrderItem> OrderItems { get; set; }
}