在实体框架核心中添加实体图
问题描述:
我已经使用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一起工作。