Mvc learning Summary-using Ninject, CodeFirst, ninjectcodefirst

Source: Internet
Author: User

Mvc learning Summary-using Ninject, CodeFirst, ninjectcodefirst

1. ninject is used to decouple the program, that is, programming the interface, rather than programming the implementation class; Understanding: BLL programming the IDAL, corresponding to calling the DAL of multiple data implementations, DAL can be of SqlServer, it can be Oracle or other data media;

2. CodeFirst is a type of EF. It is used for data persistence and can be understood as the data source of the DAL layer or repository layer in the first point;

3. Main Code

Model Layer

namespace MVCCodeFirstNinject.Model{    public class EntityBase<TId>    {        public TId ID { get; set; }    }}

  

namespace MVCCodeFirstNinject.Model{    public class Product : EntityBase<int>    {        public string Name { get; set; }        public decimal Price { get; set; }    }}

At the irepository layer, I isolated the warehousing interface layer and saw that many people put it in the domain;

namespace MVCCodeFirstNinject.IRepository{    public interface IProductRepository    {        IQueryable<Product> Products { get; }    }}

IQueryable is returned here. Understanding: IQueryable adds the where clause when processing SQL statements, while IEumerable reads all data to the memory and then filters the where clause. Of course, IQueryable will consume performance when processing the where clause for linq conversion; therefore, IQueryable is used for a large amount of data, whereas IEumerable;

The CodeFirst of EF is independent, and the data layer: CodeFirst needs to be referenced by EF;

Namespace MVCCodeFirstNinject. codeFirst {public class EFDbContext: DbContext {public DbSet <Product> Products {get; set;} protected override void OnModelCreating (DbModelBuilder modelBuilder) {modelBuilder. entity <Product> (). toTable ("tProduct"); // specify the table name // set the field name modelBuilder corresponding to the database. entity <Product> (). property (p => p. ID ). hasColumnName ("ProductID "). hasColumnType ("int ");}}}

You also need to add a connection string in web. config:

<connectionStrings>        <add name="EFDbContext" connectionString="Data Source=.;Initial Catalog=Product;User ID=sa;Password=sa" providerName="System.Data.SqlClient" />    </connectionStrings>

The preceding two steps enable CodeFirst Data Reading;

Add the repository layer, which can be understood as: multiple data sources define different warehouses. For example, CodeFirst is used now (CodeFirst is called here to achieve data persistence), and programs will be expanded in the future, it can be extended to other layers, such as the DAL of SQL Server for Layer 3, or Oracle;

namespace MVCCodeFirstNinject.Repository{    public class ProductRepository : IProductRepository    {        private EFDbContext ef = new EFDbContext();        public IQueryable<Product> Products        {            get { return ef.Products; }        }    }}

The next step is the basic device, which defines the factory class at the beginning of the mvc access, which is defined in the infrastructure layer:

Namespace MVCCodeFirstNinject. infrastructure {// Infrastructure layer: Specify the Ninject factory mode mapped by mvc. // call Ninject in mvc mode to map a view that should be used in the controller, // if multiple views exist, the view should contain multiple subviews to display multiple model data in one page: public class NinjectControllerFactory: DefaultControllerFactory {private IKernel ik; public NinjectControllerFactory () {ik = new StandardKernel (); AddNinjectIoc ();} private void AddNinjectIoc () {ik. bind <IProductRepository> (). to <ProductR Epository> ();} protected override IController GetControllerInstance (RequestContext requestContext, Type controllerType) {// ik. Get returns controllerType = null? Null: (IController) ik. Get (controllerType );}}}

The usage of Ninject is included here, that is, the ik is defined first, and then the bining is specified with bind. Finally, the access method of mvc is re-called and the get method is used to return the class to be used, that is, the IRepository class in the warehouse;

The last is mvc. Add Ninject's factory model registration to mvc:

Namespace MVCCodeFirstNinject. web {public class MvcApplication: System. web. httpApplication {protected void Application_Start () {AreaRegistration. registerAllAreas (); WebApiConfig. register (GlobalConfiguration. configuration); FilterConfig. registerGlobalFilters (GlobalFilters. filters); RouteConfig. registerRoutes (RouteTable. routes); // call ControllerBuilder to add Ioc. current. setControllerFactory (new NinjectControllerFactory ());}}}

Add the mvc Controller: (mvc adds the controller and then adds the corresponding View to the Controller method)

namespace MVCCodeFirstNinject.Web.Controllers{    public class ProductController : Controller    {        private IProductRepository _repository;        //        // GET: /Product/        public ViewResult Index()        {            return View(_repository.Products);        }               public ProductController(IProductRepository repository)        {            _repository = repository;        }    }}

The constructor of the controller introduces the initialization of the corresponding IProductRepository (ing comes from the factory class of the Basic device layer, pay attention to the Inheritance and re-creation of this class ), get the corresponding data layer read (here: programming the interface );

Finally, add a view to read the data:

@model IQueryable<MVCCodeFirstNinject.Model.Product>@{    ViewBag.Title = "Index";}@{    string str = "";    foreach (var p in Model)    {        str += "<p>" + p.Name + "</p>";    }    }@str

  


Net mvc in non-codefirst, how to set a field to a non-empty description like in codefirst?

Use MetadataType. For example:

Specifies the metadata class to be associated with the data model class
Using System. ComponentModel. DataAnnotations;
// Specify the metadata class to be associated with the data model class
[MetadataType (typeof (Product_MetaData)]
Public partial class Product
{
Public Product ()
{
This. ProductGuid = Guid. NewGuid ();
This. AddTime = DateTime. Now;
}
Public class Product_MetaData
{
Public Guid ProductGuid {get; set ;}
[Required (ErrorMessage = "product name cannot be blank")]
Public string ProductName {get; set ;}
Public DateTime AddTime {get; set ;}
}
}
After this association, you can perform initialization, verification, and custom verification error information, which is equivalent to extending the Model object.
Because the verification is done at the Model layer, so that the maintenance is good, metadata needs to be done and associated with the ADO. NET object data Model.
For example, if the product price needs to be verified, see
[RegularExpression (@ "^ (\ d +) (. \ d + )? ", ErrorMessage =" Incorrect price format ")]
[Required (ErrorMessage = "*")]
Public double ProductPrice {get; set ;}
Right? Is it a good extension? You need to modify and verify it later. You only need to modify it in this metadata class.

Verify the code when calling the Controller Layer
If (! ModelState. IsValid)
{
Return View ();
}

All aspnet mvc3 projects are developed using codefirst, right?

Your answer is basically correct, but there is always an accident. I am currently working on the MVC3 project, so this is not the case.

In fact, you are a method of development. Your favorite and suitable projects are the best. Of course, the premise is to meet the needs of the project, rather than simply relying on your own interests.

Hey. It's off duty ,. Eat now.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.