I am trying to add a property of a class from a query. I have two classes "Article & Source with manytomany relationship. source:
public class Source
{
public Source()
{
this.Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public int ApiId { get; set; }
public string? FullName { get; set; }
public string? Bio { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
article :
public class Article
{
public Article()
{
this.Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public int ApiId { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public double Rating { get; set; }
public DateTime? AirDate { get; set; }
public virtual ICollection<Source> Cast { get; set; }
}
in my method, first I do a split then a query. I want to add the results of the query to the property Cast of my class Article
public void AddArticle(string name, string summary = null, string sources = " ", double rating = 5, DateTime? airDate = null)
{
using (var db = this._dataContextFactory.Create())
{
var sourcesDb = sources.Split(',').Select(a => db.Sources.Where<Source>(s => s.FullName == a).Include(s => s.Articles)).ToList();
db.Articles.Add(new Article()
{
Cast = (ICollection<Source>)sourcesDb.ToList(),
AirDate = airDate,
Rating = rating,
Summary = summary,
Title = name
}); ;
db.SaveChanges();
}
}
when I execute the code I have the following error :
exception {"Unable to cast object of type 'System.Collections.Generic.List1[Microsoft.EntityFrameworkCore.Query.IIncludableQueryable2[test1Project.Models.Source,System.Collections.Generic.ICollection1[test1Project.Models.Article]]]' to type 'System.Collections.Generic.ICollection1[test1Project.Models.Source]'."} System.InvalidCastException
Thank you for your help
Thank you , I edited my method to
var arrayOfString = sources.Split(','); var sourcesDb =db.Sources.Where(s => arrayOfString.Contains(s.FullName)).Include(s => s.Articles).ToList();and it works . Thanks again –