C# &引用;序列包含多个元素;将数据库数据转换为列表时
标签C# &引用;序列包含多个元素;将数据库数据转换为列表时,c#,entity-framework,entity-framework-core,C#,Entity Framework,Entity Framework Core,标签 公共类标记 { 公共标签() { NoteTags=newhashset(); } 公共int ID{get;set;} 公共字符串名称{get;set;} 公共虚拟ICollection注释标记{get;set;} } EF代码在映射过程中首先使用约定。其中一个约定是,它将名为Id或TypenameId的属性视为主键(如果不使用Key属性或自定义映射),并且因为它不敏感地执行属性名比较,所以会抛出异常 此外,您的NoteTag表有NoteId(FK)和TagId(FK),但您的Note有
公共类标记
{
公共标签()
{
NoteTags=newhashset();
}
公共int ID{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection注释标记{get;set;}
}
EF代码在映射过程中首先使用约定。其中一个约定是,它将名为Id或TypenameId的属性视为主键(如果不使用Key属性或自定义映射),并且因为它不敏感地执行属性名比较,所以会抛出异常
此外,您的NoteTag表有NoteId(FK)和TagId(FK),但您的Note有ID(PK),Tag有ID(PK)
注:
标签
公共类标记
{
公共标签()
{
NoteTags=newhashset();
}
//主键
public int TagId{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection注释标记{get;set;}
}
那么,你认为我只需要更改钥匙的名称吗?使用一些当前存在的数据这样做安全吗?不,模型现在已经更改,因此您必须删除数据库。好的,所以我更改了名称,影响same@Ludwik11对不起,那没用。我可以建议另外一件事var allNotes=db.Notes.Include(x=>x.NoteTags)。然后Include(x=>x.Tag)。其中(dbnote=>tags.All(givenTag=>dbnote.NoteTags.Any(dbNoteTag=>dbNoteTag.Tag.Name==givenTag));
//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();
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; }
}
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; }
}