2011-02-20 34 views
12

Có một cơ sở dữ liệu hiện có có tên Northwind với ứng dụng biểu mẫu web. khi chạy ứng dụng nêu lên một lỗi: 'tên cột không hợp lệ CategoryCategoryID'. có ai giúp tôi không ?. cảm ơn trước !!Tên mã không hợp lệ đầu tiên của EF Mã "Danh mụcCategoryID"

Category.cs:

public class Category 
{ 

    public int CategoryID { get; set; } 
    // public int ID { get; set; } 
    public string CategoryName { get; set; } 
    public string Description { get; set; } 
    public byte[] Picture { get; set; } 
    public virtual ICollection<Product> Products { get; set; } 
} 

Product.cs:

public class Product 
{ 

    public int ProductID { get; set; } 
    //public int ID { get; set; } 
    public string ProductName { get; set; } 
    public Decimal? UnitPrice { get; set; } 
    public bool Discontinued{ get; set; } 
    public virtual Category Category{ get; set; } 
} 

Northwind.cs

public class Northwind: DbContext 
{ 
    public DbSet<Product> Products { get; set; } 
    public DbSet<Category> Categorys{ get; set; } 
} 

products.aspx

protected void Page_Load(object sender, EventArgs e) 
{ 
    Northwind northwind = new Northwind(); 

    var products = from p in northwind.Products 
    where p.Discontinued == false 
    select p; 

    GridView1.DataSource = products.ToList(); 
    GridView1.DataBind(); 
} 
+1

lý do tại sao bạn nhận xét Id? có lẽ lược đồ sai khớp – paragy

Trả lời

13

Một cách để giải quyết việc này là thêm một tài sản FK mới để tổ chức Product của bạn:

public class Product 
{ 
    public int ProductID { get; set; }   
    public string ProductName { get; set; } 
    public Decimal? UnitPrice { get; set; } 
    public bool Discontinued { get; set; } 
    [ForeignKey("Category")] 
    public int CategoryId { get; set; } 

    public virtual Category Category { get; set; } 
} 
+5

Tại sao điều này xảy ra ??? –

+0

ForeignKey nằm trong System.ComponentModel.DataAnnotations; không gian tên và cũng có thể được đặt trên [ForeignKey ("Category")] public virtual Category Category {get; bộ; } –

+0

Làm thế nào để làm cho nó tùy chọn? – Shimmy

Các vấn đề liên quan