Chinaunix首页 | 论坛 | 博客
  • 博客访问: 847911
  • 博文数量: 366
  • 博客积分: 10267
  • 博客等级: 上将
  • 技术积分: 4290
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 14:04
文章分类

全部博文(366)

文章存档

2012年(366)

分类: 系统运维

2012-03-10 19:42:24

在这里我们使用code frist,

User

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

Role

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

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

1.关联表的名字

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

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

modelBuilder.Entity().Property(i => i.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity()
.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;

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




阅读(1007) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~