“序列包含多个元素”,同时将数据库数据转换为列表

本文关键字:数据库 数据 转换 列表 包含多 元素 | 更新日期: 2023-09-27 18:28:51

//searchText contains tags in one string. E.g. "programming javascript angular"
string[] separators = { " " };
//Splitting string to array
List<string> tags = searchText.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToList();
//getting notes which all tags equals tags given by user            
var allNotes = db.Notes.Where(dbnote => tags.All(givenTag => dbnote.NoteTags.Any(dbNoteTag => dbNoteTag.Tag.Name == givenTag))).Include(x => x.NoteTags).ThenInclude(x => x.Tag);
var dataToList = allNotes.ToList();

问题出现在最后一行。

类型为"System.InvalidOperationException"的异常发生在 mscorlib.dll但没有在用户代码中处理

其他信息:序列包含多个元素

注意:

public class Note
    {
        public Note()
        {
            NoteTags = new HashSet<NoteTag>();
        }
        public int ID { get; set; }
        public virtual ICollection<NoteTag> NoteTags { get; set; }
        [...]
    }

注释标记

public class NoteTag
{
    public int NoteId { get; set; }
    public Note Note { get; set; }
    public int TagId { get; set; }
    public Tag Tag { get; set; }
}

标记

public class Tag
{
    public Tag()
    {
        NoteTags = new HashSet<NoteTag>();
    }
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<NoteTag> NoteTags { get; set; }
}

“序列包含多个元素”,同时将数据库数据转换为列表

EF 代码首先在映射期间使用约定。约定之一是它将名为 Id 或 TypenameId 的属性视为主键(如果不使用 Key 属性或自定义映射(,并且由于它不区分属性名称大小写,因此会引发异常。

此外,您的NoteTag表具有NoteId(FK(和TagId(FK(,但您的Note具有ID(PK(,而Tag具有ID(PK(注意:

public class Note
    {
        public Note()
        {
            NoteTags = new HashSet<NoteTag>();
        }
        //primary key
        public int NoteId { get; set; }
        public virtual ICollection<NoteTag> NoteTags { get; set; }
        [...]
    }

注释标记

public class NoteTag
{
    public int NoteId { get; set; }
    public Note Note { get; set; }
    public int TagId { get; set; }
    public Tag Tag { get; set; }
}

标记

public class Tag
{
    public Tag()
    {
        NoteTags = new HashSet<NoteTag>();
    }
    // primary key
    public int TagId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<NoteTag> NoteTags { get; set; }
}