MVC3、如何应用EntityFramework 连接MySql 数据库

时间:2023-03-09 19:07:19
MVC3、如何应用EntityFramework  连接MySql 数据库

原文:MVC3、如何应用EntityFramework 连接MySql 数据库

新的一年,新的开始。

今天总结的主题是在MySql中应用EntityFramework 的Code First模式。

开发环境:Win8 + MySql5.5 +VS 2012.

第一步是在数据库中新建一个表,具体字段如下图。

MVC3、如何应用EntityFramework  连接MySql 数据库

在表中添加若干数据:

MVC3、如何应用EntityFramework  连接MySql 数据库

数据建好之后,下面就是在项目中引用EntityFramework了。

二,在项目中新建一个实体类Product

public class Product
    {
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }

注意,成员名要与数据库中的名相同。

然后新建一个接口 IProductRepository

public  interface IProductRepository
    {
        IQueryable<Product> Products { get; }
    }

之后,是实现接口的类

public class EFProductRepostitory:IProductRepository

{

private EFDbContext context = new EFDbContext();

public IQueryable<Entities.Product> Products

{

get { return context.Products; }

}

}

实现与数据库上下文关联

public class EFDbContext:DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Friend> Friends { get; set; }
    }

然后在Controller中实现调用

public class ProductController : Controller
{
private int pageSize = ;
private IProductRepository repository; public ProductController(IProductRepository productRepository)
{
repository = productRepository;
} public ViewResult List(int page=)
{
return View(repository.Products
.OrderBy(p=>p.ProductID)
.Skip((page-)*pageSize)
.Take(pageSize));
} }

在Ninject产生Controller的类中绑定。

 public class NinjectControllerFactory:DefaultControllerFactory
{
private IKernel ninjectKernel; public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
} protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
} public void AddBindings()
{
//Mock<IProductRepository> mock = new Mock<IProductRepository>();
//mock.Setup(m => m.Products).Returns(new List<Product> {
// new Product{ Name=" football", Price=25},
// new Product{ Name="basketball" , Price=30},
// new Product{ Name="PingPang" , Price=40}
//}.AsQueryable());
//ninjectKernel.Bind<IProductRepository>().ToConstant(mock.Object);
ninjectKernel.Bind<IProductRepository>().To<EFProductRepostitory>();
ninjectKernel.Bind<IFriend>().To<EFFriend>();
}

最后需要注意的一点是,配置文件中写数据库连接的地方要与DbContext的类名保持一致。

 <connectionStrings>
<!--<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-SportStore.UI-20121214161900;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-SportStore.UI-20121214161900.mdf" />-->
<add name="EFDbContext" connectionString="Database=sportstore;Data Source=localhost;User Id=root;Password=root" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>