Asp.net 实体框架如何映射这种关系?
我有 因此,我意识到我需要第三张表,(因为徽章也在DB中定义,所以我创建了:Asp.net 实体框架如何映射这种关系?,asp.net,asp.net-mvc,entity-framework,Asp.net,Asp.net Mvc,Entity Framework,我有 因此,我意识到我需要第三张表,(因为徽章也在DB中定义,所以我创建了: User: -ID -Name Badge -ID -Name (E.G "User has made 100 posts", the same relationship as Stackoverflow) 所以现在在我的用户类中 UserBadge -ID -User -Badge (或类似的)因为…EF没有智能(我猜)自动知道“徽章”应该只包括用户匹配的徽章 我应该怎么做?我想我可以有一个自定义
User:
-ID
-Name
Badge
-ID
-Name (E.G "User has made 100 posts", the same relationship as Stackoverflow)
所以现在在我的用户类中
UserBadge
-ID
-User
-Badge
(或类似的)因为…EF没有智能(我猜)自动知道“徽章”应该只包括用户匹配的徽章
我应该怎么做?我想我可以有一个自定义的徽章获取程序,其中包含LINQ条件…如果你想获取用户的所有徽章,那么只需使用
用户。查找(1)。徽章。EF将自动过滤与用户相关的徽章。这是EF 4.3代码第一步:
Users.Find(1).Badges.Where(x => x.User == user && x.Badge = badgeIWant)
.FirstOrDefault();
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Data.Entity;
名称空间控制台
{
公共类用户
{
公共int ID{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection徽章{get;set;}
}
公众阶级徽章
{
公共int ID{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection用户{get;set;}
}
公共类上下文:DbContext
{
公共上下文()
:基数(“票数”)
{
}
公共数据库集用户{get;set;}
公共数据库集标记{get;set;}
}
班级计划
{
静态void Main(字符串[]参数)
{
上下文=新上下文();
User User=context.Users.Include(“徽章”).Where(u=>u.ID==1.SingleOrDefault();
如果(用户!=null)
{
//编写代码。
}
Console.ReadKey();
}
}
}
我已经对它进行了测试,这应该可以工作。这通常是一种多对多关系,因为用户可以有多个徽章,而一个徽章可以属于多个用户。如果运行此代码,您将发现EF创建了BadgeUsers
表,其中BadgeID和UserID作为外键。从此处,您可以查询,EF知道您使用的是哪个徽章布特。谢谢你的回复,太棒了,抱歉,但是为什么徽章中的用户集合被称为徽章?它应该被称为用户吗?@William:是的,抱歉:)。它应该被称为用户。我只是从用户模型复制粘贴,忘记了更改徽章。顺便说一句,如果你勾选它作为答案,一般的做法是投票支持这个答案(0上方的小箭头):)
Users.Find(1).Badges.Where(x => x.User == user && x.Badge = badgeIWant)
.FirstOrDefault();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace ConsoleApp
{
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Badge> Badges { get; set; }
}
public class Badge
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class Context : DbContext
{
public Context()
: base("Votes")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Badge> Badge { get; set; }
}
class Program
{
static void Main(string[] args)
{
Context context = new Context();
User user = context.Users.Include("Badges").Where(u => u.ID == 1).SingleOrDefault();
if(user != null)
{
//write your code.
}
Console.ReadKey();
}
}
}