Scenario 2: An article category contains multiple articles (article), and articles may correspond to multiple categories
The code changes for the article and category are as follows:
/// <summary>///article Information/// </summary> Public classarticle:modelbase{/// <summary> ///Category name/// </summary> Public stringName {Get;Set; } PublicIcollection<category> Categorys {Get;Set; }}
public class category:modelbase{ /// <summary> /// category name /// </SUMMARY> public Span style= "color: #0000ff;" >string Name {get ; set public icollection<article> Articles { get ; set
The "many-to-many" relationship is then defined in the onmodelcreating of the Entity Framework through the Fluent API
The following configuration generates a table property called Articlecategory in the database for ArticleID and CategoryID, respectively
Public classcmsdbcontext:dbcontextbase{ PublicCmsdbcontext ():Base(CachedConfigContext.Current.DaoConfig.Cms,NewLogdbcontext ()) { } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Database.setinitializer<CmsDbContext> (NULL); Modelbuilder.entity<Article> (). Hasmany (A =A.categorys). Withmany (c=c.articles). Map (U={U.mapleftkey ("ArticleID"); U.maprightkey ("CategoryID"); U.totable ("articlecategory"); }); Base. Onmodelcreating (ModelBuilder); } PublicDbset<category> Categorys {Get;Set; } PublicDbset<article> Articles {Get;Set; }}
Two scenarios were written to test the following results:
Public Interface icmsservice{ // get article by Article ID load the article at the same time all category information article GetArticle (int ArticleID); // get categories by Category ID load all articles under that category at the same time Category getcategory (int categoryId);}
Interface Implementation class:
Public classcmsservice:icmsservice{ PublicArticle GetArticle (intArticleID) { using(varDbContext =NewCmsdbcontext ()) { returnDbContext.Articles.Include ("Categorys"). FirstOrDefault (A = a.ID = =ArticleID); } } PublicCategory GetCategory (intcategoryId) { using(varDbContext =NewCmsdbcontext ()) { returnDbContext.Categorys.Include ("Articles"). FirstOrDefault (c = c.id = =categoryId); } }}
Here, ASP. NET MVC is used to display the results, and the model passed in the view can fetch the data directly in the model object of the views (you need to specify the type on the View page)
Public class articlecontroller:admincontrollerbase{ public actionresult Index () { varthis. Cmsservice.getarticle (1); return View (models);} }
The Razor View page is written as follows:
@model Qxun.Cms.Contract.Article@if (model! =null) { @Model. Name<br/> foreach (var in Model.categorys) { <span> @item. name</span><span>| @item. createtime</span> <br/> }}
The following results show that the categories related to the article have been loaded in. Loading articles by category The principle is the same, it is not written again.
EntityFramework multi-to-many relationship processing