EntityFrameWork one-to-multiple relationship processing, entityframework

Source: Internet
Author: User

EntityFrameWork one-to-multiple relationship processing, entityframework

Scenario 1: one Article Category contains multiple articles, and one Article can only correspond to one Category.


The code for Article and Category is as follows:

/// <Summary> // Document Information // </summary> public class Article: ModelBase {// Title public string Title {get; set ;} // public string Content {get; set ;}// Category public Category {get; set ;}}


Public class Category: ModelBase {// Category Name public string Name {get; set;} // many Articles in a certain Category are included in public ICollection <Article> Articles {get; set ;}}


The following is a key step. In OnModelCreating of Entity Framework, use the Fluent API to define the "one-to-many" relationship:

Indicates that hasales has multiple Articles from the perspective of Category. WithRequired indicates that Articles must contain the article Category.

Public class CmsDbContext: DbContextBase {public CmsDbContext (): base (CachedConfigContext. current. daoConfig. cms, new LogDbContext () {} protected override void OnModelCreating (DbModelBuilder modelBuilder) {// Database. setInitializer <CmsDbContext> (null); // defines a one-to-many relationship modelBuilder. entity <Category> (). hasMany (c => c. articles ). withRequired (a =>. category); base. onModelCreating (modelBuilder);} public DbSet <Article> Articles {get; set;} public DbSet <Category> Categorys {get; set ;}}

Write two scenarios to test the following results:

public interface ICmsService{    //Article GetArticle(int id);    Category GetCategory();    Article GetArticle();}


Use LINQ to SQL to query Category and Articles
Include (). The two tables must contain foreign key relationships. You only need to specify the class property name corresponding to the key name, and do not need to specify the result field (that is, all ing ). When a table is searched by default, the foreign key table will not be queried along with the query, and the database query will not be read until it is actually used. If Include () is used (), the specified foreign key table information is also read when reading the table.

public Category GetCategory(){    using (var session = new CmsDbContext())     {        return session.Categorys.Include("Articles").FirstOrDefault();    }}public Article GetArticle() {    using (var session = new CmsDbContext())     {        return session.Articles.Include("Category").FirstOrDefault();    }}


Here ASP. net mvc is used to display the result:
The model passed in the View can directly obtain data in the Model object of the View (you must specify the type on the View page), and The ViewData data can also be obtained on the View page (mandatory conversion is required)

public class CategoryController : AdminControllerBase{    //    // GET: /Cms/Category/    public ActionResult Index()    {        var model = this.CmsService.GetCategory();        ViewData["Acticle"] = this.CmsService.GetArticle();        return View(model);    }}

View page:

@ Using Qxun. framework. contract @ using Qxun. framework. web. controls @ using Qxun. cms. contract @ using Qxun. web @ {var secondPosition = ViewData ["Acticle"] as Qxun. cms. contract. article;} @ model Qxun. cms. contract. category 

Display result:


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.