【问题标题】:Creating MVC application using Razor Engine and EF CodeFirst使用 Razorengine 和 EF Code First 创建 MVC 应用程序
【发布时间】:2012-07-07 20:58:59
【问题描述】:

我正在练习实体框架。我正在使用 Razor Engine 和 EF Code First 练习 Asp.net MVC 框架。在实践中,我发现问题很少。问题是实体框架没有在我的 SQL 中创建数据库。 我正在使用带有 MSSQL 2008 的 VisualStudio 2011 Beta 版本。我不知道问题出在哪里。 需要帮助。以下是我的代码:

    Person.cs

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

namespace MvcDemo.Data
{
    public class Person
    {
        [Key]
        public int PersonID { get; set; }

        [Required]
        [StringLength(40)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(30)]
        public int LastName { get; set; }

        public int? Age { get; set; }

        [ForeignKey("PrefixID")]
        public Prefix Prefix { get; set; }


        [Required]
        public int PrefixID { get; set; }

    }
}

    Prefix.cs

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

namespace MvcDemo.Data
{
    public class Prefix
    {
        public int PrefixID { get; set; }

        [Required]
        [StringLength(20)]
        public string PrefixName { get; set; }
    }
}

MvcContext.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using MvcDemo.Data;


namespace MvcDemo.DataAccess
{
    public class MvcContext : DbContext
    {
        public MvcContext()
            : base("name = MvcDemoApp")
        {
        }
        public DbSet<Person> People { get; set; }

        public DbSet<MvcDemo.Data.Prefix> Prefix { get; set; }

    }
}

ConnectionString:
<connectionStrings>
    <add name="MvcDemoApp" 
         connectionString="Server=.;Initial Catalog=MvcDemoApp;Integrated Security=true" 
  providerName="System.Data.SqlClient" />

【问题讨论】:

    标签: asp.net-mvc entity-framework razor ef-code-first


    【解决方案1】:

    如果这是您的所有代码,那么没有创建数据库也就不足为奇了。没有对数据库执行命令的代码。一旦你开始迭代例如MvcContext.People 或执行一些插入操作,您会注意到数据库已创建。

    【讨论】:

      【解决方案2】:

      网上有很多循序渐进的例子。我会选择其中一个,然后走一遍;你可以试试这个,例如:http://msdn.microsoft.com/en-us/data/gg685467.aspx。它应该涵盖帮助您入门的大部分基础知识。

      如果您更喜欢视频而不是文字,请搜索 Channel 9pluralsight

      【讨论】:

        【解决方案3】:

        您应该操作包管理器控制台来执行此操作。

        打开包管理器控制台窗口并运行“update-database”命令,该命令仍然存在错误,因此您需要在 DbContext 文件中指定“startupprojectname”参数来执行它和连接字符串。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多