[英]Add a graph of entities in Entity Framework Core
我已经使用EF Core 1.1.0的代码优先方法在SQL数据库中创建实体。
我的某些实体具有到其他实体的导航属性(一对一或一对多)。
问题是,当我尝试添加具有导航属性的实体时,成功添加了根实体,但没有添加相关实体。
这是下面的代码:
public class PopcornContext : DbContext
{
public PopcornContext(DbContextOptions<PopcornContext> options)
: base(options)
{
}
public virtual DbSet<Movie> MovieSet { get; set; }
}
public partial class Movie
{
public Movie()
{
this.Genres = new HashSet<Genre>();
this.Cast = new HashSet<Cast>();
}
public int Id { get; set; }
public string Url { get; set; }
public string ImdbCode { get; set; }
public string Title { get; set; }
public string TitleLong { get; set; }
public string Slug { get; set; }
public int Year { get; set; }
public virtual ICollection<Genre> Genres { get; set; }
public virtual ICollection<Cast> Cast { get; set; }
}
public class PopcornContextFactory : IDbContextFactory<PopcornContext>
{
public PopcornContext Create(DbContextFactoryOptions options)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var optionsBuilder = new DbContextOptionsBuilder<PopcornContext>();
optionsBuilder.UseSqlServer(configuration["SQL:ConnectionString"]);
return new PopcornContext(optionsBuilder.Options);
}
}
当我插入像这样的电影时:
using (var context = new PopcornContextFactory().Create(new DbContextFactoryOptions()))
{
var movie = new Database.Movie
{
ImdbCode = movieJson.ImdbCode,
TitleLong = movieJson.TitleLong,
Year = movieJson.Year,
Cast = movieJson.Cast.Select(cast => new Database.Cast
{
ImdbCode = cast?.ImdbCode,
SmallImage = cast?.SmallImage,
CharacterName = cast?.CharacterName,
Name = cast?.Name
}).ToList(),
Genres = movieJson.Genres.Select(genre => new Database.Genre
{
Name = genre
}).ToList(),
Slug = movieJson.Slug,
Title = movieJson.Title,
Url = movieJson.Url
};
await context.MovieSet.AddAsync(movie);
await context.SaveChangesAsync();
}
电影将与其所有字段一起添加到数据库中,但类型和演员表不存在(空值)。
我已经建立了我的代码优先方法:
Add-Migration Initial
Update-Database
我错过了什么? 我很确定这段代码可以与EF6一起使用。
我知道了。 实际上,这是EF Core中的AddAsync方法的已知错误。 非异步Add方法按预期工作。
看这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.