EntityFramework multi-to-many relationship processing

Source: Internet
Author: User

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

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.