如何在Entity-Framework 5中使用无状态对象更新多对多关系实体

时间:2013-10-02 13:56:56

标签: c# entity-framework dependency-injection entity-framework-5

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

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");
    });
   ....
 }

带接口的DataRepository:

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-entity,我无法在表中添加新行。是否可以避免使用Tags_X_Media作为代码中的模型来实现此功能,或者这是添加或删除此实体的唯一方法吗?

0 个答案:

没有答案