我尝试编写一种通用存储库来添加方法。一切都可以添加,但我有一个与两个具有 FOREIGN KEY 的表相关的表。但由于外键而无法工作
public class DomainRepository<TModel> : IDomainRepository<TModel> where TModel : class
{
private ObjectContext _context;
private IObjectSet<TModel> _objectSet;
public DomainRepository(ObjectContext context)
{
_context = context;
_objectSet = _context.CreateObjectSet<TModel>();
}
// do something...
public TModel Add<TModel>(TModel entity) where TModel : IEntityWithKey
{
EntityKey key = _context.CreateEntityKey(entity.GetType().Name, entity);
_context.AddObject(key.EntitySetName, entity);
_context.SaveChanges();
return entity;
}
// do something...
}
调用存储库:
// insert-update-delete
public partial class AddtoTables
{
public table3 Add(int TaskId, int RefAircraftsId)
{
using (DomainRepository<table3> repTask = new DomainRepository<table3>(new TaskEntities()))
{
return repTask.Add<table3>(new table3() { TaskId = TaskId, TaskRefAircraftsID = RefAircraftsId });
}
}
}
如果此表包含外键关系,如何添加新值?