1

我用以下实体制作了一个代码优先模型

public abstract class Model
{
  public Guid Id { get; set; }
}

public class Media : Model
{
  public string Name { get; set; }
  public IList<Tag> Tags { get; set; }
}

public class Tag : Model 
{
  public string Name { get; set; }
  public IList<Media> Media { get; set; }
}

语境:

public DbSet<Media> Media { get; set; }
public DbSet<Tag> Tags { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Tag>().HasMany(x => x.Media).WithMany(x => x.Tags).Map(x =>
    {
       x.ToTable("Tags_X_Media");
       x.MapLeftKey("TagId");
       x.MapRightKey("MediaId");
    });
   ....
 }

具有接口的数据存储库:

public interface IDataRepository
{
  T Update<T>(T model) where T : Model;
}

public class DataRepository : IDataRepository
{
  public T Update<T>(T model) where T : Model
  {
    return PerformAction((context) =>
    {
      context.Set<T>().Attach(model);
      context.Entry(model).State = System.Data.EntityState.Modified;
      context.SaveChanges();
      return model;
    }
  }

    private T PerformAction<T>(Func<Context, T> toPerform) where T : Model
    {
        using (Context context = new Context())
        {
            context.Configuration.AutoDetectChangesEnabled = false;
            context.Configuration.ValidateOnSaveEnabled = true;
            context.Configuration.LazyLoadingEnabled = false;
            context.Configuration.ProxyCreationEnabled = false;
            return toPerform(context);
        }
    }
}

保存示例:

//get uses .Include(x => x.Tags)
var media = DbRepository.Get<Media>(p => p.Id == "the id", x => x.Tags);

media.Tags.Add(new Tag { Name = "A tag name" });
DbRepository.Update<Media>(media);

如上面的保存示例所示,在交叉表 Tags_X_Media 中添加和删除实体的正确方法是什么?如果我将状态设置为更改,例如 Media.Tags,则此状态将应用于 dbo.Tags 中的标签实体,并且我无法在表中添加新行。是否可以在代码中避免将 Tags_X_Media 作为模型来使其工作,或者这是添加或删除此实体的唯一方法?

4

0 回答 0