我的技术问题非常简短:如何更新使用Code First Migration时创建的关系表?
此处 StockKeepingUnitFeature 表是自动创建的,但我没有任何对象类来更新该表。我们该怎么办?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Entity<StockKeepingUnit>()
.HasMany(b => b.Feature)
.WithMany(a => a.StockKeepingUnit)
.Map(m => m.MapLeftKey("StockKeepingUnitId")
.MapRightKey("FeatureId")
.ToTable("StockKeepingUnitFeature"));
}
谢谢!
答案 0 :(得分:0)
这里的解决方案:我发现微软的链接,非常有帮助! Relationships, Navigation Properties, and Foreign Keys
此后我的代码更新了关系表:
public IQueryable<TEntity> AllIncluding(params Expression<Func<TEntity, object>>[] includeProperties)
{
IQueryable<TEntity> query = context.Set<TEntity>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
/// <summary>
/// Update the relational StockKeepingUnitFeature table
/// </summary>
/// <param name="stockKeepingUnitSlug"></param>
/// <param name="featureSlug"></param>
/// <returns></returns>
public bool AddFeatureToStockKeepingUnit(string stockKeepingUnitSlug, string featureSlug)
{
StockKeepingUnit sku = this.AllIncluding(stockKeepingUnit => stockKeepingUnit.Feature).Where(s => s.Slug == stockKeepingUnitSlug).FirstOrDefault();
Feature feature = context.Features.FirstOrDefault(f => f.Slug == featureSlug);
if (feature != null && sku != null)
{
sku.Feature.Add(feature);
context.StockKeepingUnits.Attach(sku);
context.SaveChanges();
return true;
}
return false;
}
/// <summary>
/// Update the relational StockKeepingUnitFeature database
/// </summary>
/// <param name="stockKeepingUnitSlug"></param>
/// <param name="featureSlug"></param>
/// <returns></returns>
public bool RemoveFeatureFromStockKeepingUnit(string stockKeepingUnitSlug, string featureSlug)
{
StockKeepingUnit sku = this.AllIncluding(stockKeepingUnit => stockKeepingUnit.Feature).Where(s => s.Slug == stockKeepingUnitSlug).FirstOrDefault();
Feature feature = context.Features.FirstOrDefault(f => f.Slug == featureSlug);
if (feature != null && sku != null)
{
context.Entry(feature).Collection(s => s.StockKeepingUnit).CurrentValue = null;
context.SaveChanges();
return true;
}
return false;
}
希望它对社区有用,
干杯