2
我已經使用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一起工作。