C#:使用实体框架代码访问数据库 - 第一个

时间:2017-04-13 13:08:05

标签: asp.net asp.net-mvc entity-framework asp.net-mvc-4

我是ASP.NET MVC的初学者,尝试使用Entity Framework Code-First进行数据库访问,但是我收到了一个错误。我在stackoverflow上看到了很多问题,但它们与我的情况无关。我的错误是。

  

类型' System.InvalidOperationException'的例外情况发生在EntityFramework.dll中但未在用户代码中处理

     

其他信息:无法完成操作。提供的SqlConnection不指定初始目录或AttachDBFileName。

     在var brands = lensStoreDB.Brands.ToList();

的LensStoreController.cs中

LensStoreController.cs

public ActionResult Index()
{
    var brands = lensStoreDB.Brands.ToList();
    return View(brands);
}

Brands.cs,Lenses.cs和Manufacturer.cs是我的Model类

Brand.cs

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

namespace EyeContactLens.Models
{
    public class Brands
    {
        [Key]
        public int BrandId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<Lenses> Lenses { get; set; }

    }

}

Lenses.cs

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

namespace EyeContactLens.Models
{
    public class Lenses
    {
        [Key]
        public int LensesId { get; set; }
        public int BrandId { get; set; }
        public int ManufacturerId { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string LensManuUrl { get; set; }
        public Brands Brand { get; set; }
        public Manufacturer Manufacturer { get; set; }
    }
}

Manufacturer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EyeContactLens.Models
{
    public class Manufacturer
    {
        public int ManufacturerId { get; set; }
        public string Name { get; set; }
    }
}

我还有一个班级SampleData.cs,我希望在浏览器上显示其数据。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace EyeContactLens.Models
{
    public class SampleData : DropCreateDatabaseIfModelChanges<EyeContactLensEntities>
    {
        protected override void Seed(EyeContactLensEntities context)
        {
            var brands = new List<Brands>
            {
                new Brands { Name = "Cooper Vision"},
                new Brands { Name = "Fresh Kon"},
                new Brands { Name = "Flexcon"},
                new Brands { Name = "Avaira"},
            };

            var manufacturer = new List<Manufacturer>
            {
                 new Manufacturer { Name = "Oculus"},
                 new Manufacturer { Name = "Alcon (CIBA Vision)"}
            };

            new List<Lenses>
            {
                new Lenses { Title = "Biofinity Contact Lens", Brand = brands.Single(b => b.Name == "Cooper Vision"), Price = 8.99M, Manufacturer = manufacturer.Single(a => a.Name == "Alcon (CIBA Vision)"), LensManuUrl = "/Content/Images/placeholder.gif" },
                new Lenses { Title = "FreshKon A55", Brand = brands.Single(b => b.Name == "Fresh Kon"), Price = 18.99M, Manufacturer = manufacturer.Single(a => a.Name == "Oculus"), LensManuUrl = "/Content/Images/placeholder.gif" },
                new Lenses { Title = "Flexcon Blue Tint UV Prolong wear (BUPW) (45%)", Brand = brands.Single(b => b.Name == "Flexcon"), Price = 81.99M, Manufacturer = manufacturer.Single(a => a.Name == "Oculus"), LensManuUrl = "/Content/Images/placeholder.gif" },
                new Lenses { Title = "Frequency 55 Toric Contact Lens", Brand = brands.Single(b => b.Name == "Cooper Vision"), Price = 10.99M, Manufacturer = manufacturer.Single(a => a.Name == "Alcon (CIBA Vision)"), LensManuUrl = "/Content/Images/placeholder.gif" },
                new Lenses { Title = "Freshkon N-Hance Toric", Brand = brands.Single(b => b.Name == "Fresh Kon"), Price = 11.99M, Manufacturer = manufacturer.Single(a => a.Name == "Oculus"), LensManuUrl = "/Content/Images/placeholder.gif" }
            }.ForEach(a => context.Lenses.Add(a));
        }
    }
}

我还将EyeContactLensEntities.cs用作DbContext

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace EyeContactLens.Models
{
    public class EyeContactLensEntities : DbContext
    {
        public DbSet<Lenses> Lenses { get; set; }
        public DbSet<Brands> Brands { get; set; }
    }
}

web.config

<connectionStrings>
    <add name="EyeContactLensEntities" connectionString="Data Source=|DataDirectory|EyeContactLens.sdf" providerName="System.Data.SqlClient"/>
</connectionStrings>

的Global.asax.cs

protected void Application_Start()
{
    System.Data.Entity.Database.SetInitializer(new Models.SampleData());

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

2 个答案:

答案 0 :(得分:0)

您的连接字符串错误。 您需要在配置字符串中提供的内容是数据源(例如SQL Server实例)和初始目录(例如该服务器上的数据库)。

可以使用Sql Server Management Studio打开.sdf,从那里你应该能够看到你需要连接到什么。

编辑: 有关如何使用SQL Server Management Studio执行此操作的链接: How do you open an SDF file (SQL Server Compact Edition)?

答案 1 :(得分:0)

您需要更改连接字符串中的providerName:

<connectionStrings>
    <add name="EyeContactLensEntities" 
         connectionString="Data Source=|DataDirectory|EyeContactLens.sdf" 
         providerName="System.Data.SqlSqlServerCe.4.0"/>
</connectionStrings>

您需要安装SQL Server Compact EF Nuget包:

Install-Package EntityFramework.SqlServerCompact