"序列包含多个元素"将db数据转换为List时

时间:2016-01-03 12:04:01

标签: c# entity-framework entity-framework-core

//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();

问题出现在最后一行。

  

类型&#39; System.InvalidOperationException&#39;的例外情况发生在   mscorlib.dll但未在用户代码中处理

     

附加信息:序列包含多个元素

注意:

public class Note
    {
        public Note()
        {
            NoteTags = new HashSet<NoteTag>();
        }

        public int ID { get; set; }
        public virtual ICollection<NoteTag> NoteTags { get; set; }
        [...]
    }

NoteTag

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; }
}

1 个答案:

答案 0 :(得分:0)

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; }
        [...]
    }

NoteTag

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; }
}