惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MongoDB | Blog
MongoDB | Blog
J
Java Code Geeks
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
DataBreaches.Net
腾讯CDC
GbyAI
GbyAI
I
InfoQ
博客园 - Franky
G
Google Developers Blog
Last Week in AI
Last Week in AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
Visual Studio Blog
Vercel News
Vercel News
博客园_首页
MyScale Blog
MyScale Blog
Martin Fowler
Martin Fowler
N
Netflix TechBlog - Medium
V
V2EX
T
The Blog of Author Tim Ferriss
M
MIT News - Artificial intelligence
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
大猫的无限游戏
大猫的无限游戏
The GitHub Blog
The GitHub Blog

博客园 - Xia.CJ

C# 委托 node.js中连接mongodb(Please ensure that you set the default write...)解决办法 node.js api解读之file system模块 Node.js小技巧 在windows上安装新版node.js-node.js学习笔记 Asp.Net MVC部暑托管服务器iis7提示403错误解决方法 mvc3中使用unobtrusive时,ajax更新加载页面后验证失效解决方法 ashx中使用HttpContext.Current.Session ,出现未将对象引用设置到实例上 搜索引擎(google/百度)高级指令 在mvc3中使用uploadify上传组件User.isAuthenticated等于false解决方法 MVC中用Html.RenderPartial还是Html.RenderAction或者Html.Partial-Xia.CJ 在_Layout使用Html.RenderAction的问题-MVC3(Razor)问题 无法删除此对象,因为未在 ObjectStateManager 中找到它-entity framework删除时 Javascript数组(array)操作 序列化类型 System.Data.Entity.DynamicProxies 的对象时检测到循环引用 entity framework(EF)_code first复杂类型(Complex Types)问题 JQuery获取checkbox值,checkbox全选,操作checkbox JQuery操作Select JQuery动态创建DOM、表单
entity framework多对多关系查询
Xia.CJ · 2012-03-10 · via 博客园 - Xia.CJ

在这里我们使用code frist,

User

 public string UserId { get; set; }
public string UserName { get; set; }
public virtual IList<Role> Roles { get; set; }

Role

 public string RoleId { get; set; }
public string RoleName { get; set; }
public virtual IList<User> Users { get; set; }

现在,我们要做什么呢?控制两件事

   1.关联表的名字

   2.在关联表中的两个列名

通过下面的代码可以实现:

 modelBuilder.Entity<User>().Property(i => i.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<User>()
.HasMany(u=>u.Roles)
.WithMany(u=>u.Users)
.Map(m =>
{
m.ToTable("UsersInRoles");
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
});

这样我们这完成了配置.

多对多

而我们要查询的时候可以这样做:

 var result = from u in db.Users
from r in u.Roles
where r.RoleId == “roleid”
select u;

我想聪明的你,一定可以查询出其他符合你需要的方法

posted @ 2012-03-10 16:47  Xia.CJ  阅读(2287)  评论()    收藏  举报