0

我最近开始使用 ASP.NET MVC 和实体框架。

使用现有数据库,我尝试将我的类映射到数据库表。没有成功。

让我向您展示我的数据库表:

->类别 --> Id (PK)--> 标题--> 描述

->产品 --> Id (PK) --> 名称 --> 描述 --> 价格 --> 类别 (FK -> CategoryTree)

->分类 树 --> Id (PK) --> ParentCategory (FK -> Category) --> ChildCategory (FK -> Category)

现在,我的实体框架类:

class Products
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public virtual ICollection<CategoryTree> Category { get; set; }
}

class Categories
{
    public int categoriesId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

class CategoryTree
{
    public int Id { get; set; }
    public virtual ICollection<Categories> ParentCategory { get; set; }
    public virtual ICollection<Categories> ChildCategory { get; set; }
}

class EFDbContext : DbContext
{
    public DbSet<Products> Products { get; set; }
    public DbSet<Categories> Categories { get; set; }
    public DbSet<CategoryTree> CategoryTree { get; set; }
}

如果我启动应用程序,编译器会提示以下错误消息: 支持“EFDbContext”上下文的模型自创建数据库以来已更改。考虑使用 Code First 迁移来更新数据库 ( http://go.microsoft.com/fwlink/?LinkId=238269 )。

我希望有人可以帮助我理解这一点;-)

此致

4

3 回答 3

2

In the Application_Start() method of your Global.asax.cs, add the following line:

Database.SetInitializer<EFDbContext>(null);

That will stop Entity Framework from checking for changes to your model since the creation of your database.

于 2013-04-23T20:04:31.080 回答
1

对于现有数据库,我建议使用EF 电动工具进行逆向工程以生成 POCO 类。

于 2013-04-23T19:52:53.353 回答
1

我可以从Categories.Id数据库和Categories.categoriesId模型中的上述信息 id 中看到的唯一区别(假设没有错字)。

还要检查列的可空性,例如Product.Price在模型中可以为空,在数据库中是这样吗?

我还可以建议,生成一个与您的模型名称不同的新数据库并与现有数据库进行比较。db 名称在连接字符串中指定,因此向您的 DbContext 类添加一个构造函数并传入连接字符串,

internal class EFDbContext : DbContext
{
    public EFDbContext(string connectionString) : base(connectionString)
    {

    }
于 2013-04-23T20:16:30.880 回答