Tôi đang cố gắng để truy vấn Posts
dựa trên một danh sách các Tags
:LINQ nhiều-nhiều ngã tư
public class Post
{
public int? Id {get;set;}
public string Name {get;set;}
public virtual ICollection<Tag> Tags {get;set;}
}
public class Tag
{
public int? Id {get;set;}
public string Name {get;set;}
public vritual ICollection<Post> Posts {get;set;}
}
Bây giờ tôi muốn quay trở lại bài viết dựa trên một danh sách các thẻ: IList<Tag> searchTags = ParseTagsFromSearchString("tag1,tag2,tag3"); // this function checks the tags in the database, so all the primary keys are available in the list
Khi một bài đăng chứa một hoặc nhiều thẻ cũng tồn tại trong searchTags
nó phải được bao gồm trong kết quả. Tôi đã thử những điều sau đây:
var q = from s in Context.Registrations
where s.Tags.Intersect(tagList)
select s;
Lỗi: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Models.Tag>' to 'bool'
var q = from s in Context.Registrations
where s.Tags.Any(t => tagList.Any(t2 => t.Id.Value == t2.Id.Value))
select s;
Runtime lỗi: NotSupportedException: Unable to create a constant value of type 'Models.Tag'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
Bất kỳ ý tưởng?
- cập nhật ngày 4 tháng 1: Câu trả lời trỏ đến giải pháp đúng, nhưng trong mã của tôi, tôi vẫn có NotSupportedException. Có thể các số nguyên nullable gây ra điều này vì nó không phải là một kiểu nguyên thủy?
Tôi đã thử các giải pháp thứ hai trong mã LinqPad bưu Đánh dấu Lindel và nó hoạt động.Thật không may, trong mã của tôi tôi nhận được cùng một UnsupportedException .. – Marthijn