首先在实体框架代码中进行多对多映射
我正在使用 Entity Framework 4 CTP5 Code First,并且有一个模型:
public class User {
public int UserId { get; set; }
public string Email { get; set; }
public ICollection<Customer> TaggedCustomers { get; set; }
}
public class Customer {
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<User> TaggedBy { get; set; }
}
存在多对多关系,用户可以“标记”客户,而客户可以被许多用户“标记”。我有一个正在运行的 DbContext,我可以使用
var customers = DbContext.Customers.Include(c => c.TaggedBy);
但每个客户将拥有标记该客户的所有用户来查询客户。如何将 TaggedBy 集合限制为仅包含指定 UserId 的结果?
我已经尝试过 DbContext.Customers.Include(c => c.TaggedBy.Select(x => x.Id == userId));
但这会引发错误。
I'm using Entity Framework 4 CTP5 Code First and I have a model along the lines of:
public class User {
public int UserId { get; set; }
public string Email { get; set; }
public ICollection<Customer> TaggedCustomers { get; set; }
}
public class Customer {
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<User> TaggedBy { get; set; }
}
There is a many to many relationship where a User can 'tag' a Customer and a Customer can be 'tagged' by many users. I have a working DbContext and I can query customers using
var customers = DbContext.Customers.Include(c => c.TaggedBy);
But each customer will have all users that have tagged the customer. How do I restrict the TaggedBy collection to just result with a specifed UserId?
I've tried along the lines of DbContext.Customers.Include(c => c.TaggedBy.Select(x => x.Id == userId));
but that throws an error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
EF 功能 CTP5:流畅的 API 示例 - ADO.NET 团队博客 - 网站主页 - MSDN 博客
CTP5 中的代码优先映射更改 - ADO.NET 团队博客 - 网站主页 - MSDN 博客
EF Feature CTP5: Fluent API Samples - ADO.NET team blog - Site Home - MSDN Blogs
Code First Mapping Changes in CTP5 - ADO.NET team blog - Site Home - MSDN Blogs
将您的集合标记为虚拟,然后您可以轻松地执行以下操作:
在我看来,结果会更清晰的代码。
Mark your collections as virtual and then you can easily do:
Results in much cleaner code in my opinion.