【问题标题】:The existing reference entity inserted while trying insert the root in LINQ to SQL尝试在 LINQ to SQL 中插入根时插入的现有引用实体
【发布时间】:2011-09-08 14:20:22
【问题描述】:

我在 LINQ to SQL 中有两个模型。第一个是员工,第二个是职位。 我已经在位置表中插入了位置数据。该数据将被 Employee 模型引用。

Position {
    int id,   //auto increament
    string name,
    string description, 
}

Employee {
    int id,
    string name,
    Position position,
}

我想创建员工的逻辑是:

  1. I Crate EmployeCreate 并分配员工姓名和职位 ID
  2. 使用位置存储库按 ID 查找位置。
  3. 创建员工模型分配第二步创建的职位模型
  4. 使用员工存储库插入员工并提交更改

我认为我的步骤是正确的,但是创建的位置是再次插入到数据库中,通常它没有插入,因为数据已经存在于数据库中。

我的sn-p服务如下:

EmployeService {
    //property and constructor

    AddEmployee(EmployeeCreate command) {
        var employee = EmployeeFactory.Create(command);
        var possition = _positionRepository.GetById(command.possitionId);

        using (var tx = new TransactionScope())
        {
            employee.Position = possition;
            _employeeRepository.InsertOnSubmit(employee);

            _employeeRepository.SubmitChanges();
            tx.Complete();
        }   
    }
}

编辑 我创建通用 Linq 存储库。 Employee 和 Position 是通用 Linq 存储库的扩展。

public class LinqRepository<T> : IRepository<T>, IRepository where T : class
    {

        protected readonly DataContext _dataContext;

        public LinqRepository(IDataContextProvider dataContextProvider)
        {
            _dataContext = dataContextProvider.DataContext;
        }
}

【问题讨论】:

  • 很难说是什么问题,因为您的存储库隐藏了所有与 contex 相关的工作。但是我有一些文件说员工和职位表有不同的上下文,这是真的吗?
  • @Kak YLia,我创建了通用存储库,员工和职位存储库扩展了通用存储库。我首先实例化数据上下文。并将上下文注入员工和职位存储库。因此,存储库应该使用相同的上下文。
  • 我的错,我在 Data Context LifeStyle DI 配置中犯了一个错误。

标签: c# linq-to-sql transactions


【解决方案1】:

除非您尝试跨多个上下文提交更改,否则您不应该在这里需要 TransactionScope。 SubmitChanges 在内部为请求创建一个事务,以涵盖作为提交更改的一部分请求的多个插入/更新/删除操作。唯一需要显式管理上下文的情况是当调用跨越多个上下文/连接时。

您看到的行为表明该职位可能是由您在将员工插入 _employeeRepostiory 时使用的上下文之外的上下文获取的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多