zoukankan      html  css  js  c++  java
  • EntityFrameWork Code First 多对多关系处理

    场景2: 一个文章类别(Category)下含有多篇文章(Article),而文章也可能对应多个类别

    Article和Category的代码更改如下:

    /// <summary>
    /// 文章信息
    /// </summary>
    public class Article:ModelBase
    {
        /// <summary>
        /// 类别名字
        /// </summary>
        public string Name { get; set; }
    
        public ICollection<Category> Categorys { get; set; }
    }
    public class Category : ModelBase
    {
        /// <summary>
        /// 类别名字
        /// </summary>
        public string Name { get; set; }
    
        public ICollection<Article> Articles { get; set; }
    }


    然后在Entity Framework的OnModelCreating中通过Fluent API定义“多对多”关系
    如下配置会在数据库生成一张叫ArticleCategory的表属性分别为ArticleID和CategoryID

    public class CmsDbContext : DbContextBase
    {
        public CmsDbContext():base(CachedConfigContext.Current.DaoConfig.Cms,new LogDbContext()) { 
            
        }
        protected override void OnModelCreating(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);
        }
    
        public DbSet<Category> Categorys { get; set; }
        public DbSet<Article> Articles { get; set; }
    
    }


    分别编写两个场景来测试以下结果:

    public interface ICmsService
    {
        //通过文章id获取文章同时加载该文章所有类别信息
        Article GetArticle(int articleId);
        //通过类别id获取类别同时加载该类别下所有文章
        Category GetCategory(int categoryId);
    }


    接口实现类:

    public class CmsService : ICmsService
    {
        public Article GetArticle(int articleId)
        {
            using (var dbContext = new CmsDbContext()) 
            {
                return dbContext.Articles.Include("Categorys").FirstOrDefault(a => a.ID == articleId);
            }
        }
    
        public Category GetCategory(int categoryId)
        {
            using (var dbContext = new CmsDbContext()) 
            {
                return dbContext.Categorys.Include("Articles").FirstOrDefault(c => c.ID == categoryId);
            }
        }
    }


    这里使用ASP.NET MVC来显示结果,在View中传入的model可以在视图的Model对象直接获取数据(需要在视图页指定类型)

    public class ArticleController: AdminControllerBase
    {
        public ActionResult Index() 
        {
            var models = this.CmsService.GetArticle(1);
            return View(models);
        }
    }


    Razor视图页编写如下:

    @model Qxun.Cms.Contract.Article
    
    <h2>显示文章的所有类型</h2>
    
    @if (Model!=null) 
    {
        @Model.Name<br/>
        foreach (var item in Model.Categorys) 
        {
            <span>@item.Name</span><span>|@item.CreateTime</span> <br/>      
        }
    }


    通过下面的结果发现,已经把文章相关的类别加载进来了。通过类别加载文章原理是一样的,就不再写一遍了。


  • 相关阅读:
    Alpha冲刺(4/6)
    Alpha冲刺(3/6)
    Alpha冲刺(2/6)
    Alpha冲刺(1/6)
    团队Git现场编程实战
    团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
    第一次团队展示
    第一次结对编程作业
  • 原文地址:https://www.cnblogs.com/chenjianxiang/p/4715528.html
Copyright © 2011-2022 走看看