您的位置:首页 > 移动开发

System.InvalidOperationException: The type MyContext+Northwind was not mapped.

2013-01-04 12:17 489 查看
System.InvalidOperationException: The type MyContext+Northwind was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.

错误原因:

entity framework不能将内部类与数据库匹配。

错误代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace TestCodeFirst
{
public class MyContext
     {
public class Product
{
public int ProductID { get; set; }
public int CategoryID { get; set; }
[Required(ErrorMessage = "Product Name不能为空")]
public string ProductName { get; set; }
public Decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public virtual Category Category { get; set; }
}

public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public byte[] Picture { get; set; }
public virtual ICollection<Product> Product { get; set; }
}
public class Northwind : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categorys { get; set; }
}
}
}


解决的办法:Northwind作为内部类。正确的代码如下所示

namespace TestCodeFirst
{
public class Product
{
public int ProductID { get; set; }
public int CategoryID { get; set; }
[Required(ErrorMessage="Product Name不能为空")]
public string ProductName { get; set; }
public Decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public virtual Category Category { get; set; }
}

public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public byte[] Picture { get; set; }
public virtual ICollection<Product> Product { get; set; }
}
public class Northwind:DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categorys { get; set; }
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐