1

下面是我在使用实体框架构建的 WCF 服务参考中使用的代码。如您所见,现在我一遍又一遍地使用相同的代码。是否有一种语法可以让我用泛型类型或其他可以减少使用的代码量的方法替换实体?

        var aI = (from AgentIdentification s in _db.AgentIdentification
                  where s.SymetraNumber == sNum
                  select s);

        foreach (var record in aI)
        {
            _db.AgentIdentification.DeleteObject(record);
        }

        _db.SaveChanges();

        var aG = (from Agent s in _db.Agent
                  where s.SymetraNumber == sNum
                  select s);

        foreach (var record in aG)
        {
            _db.Agent.DeleteObject(record);
        }

        _db.SaveChanges();
4

1 回答 1

1

我相信这就是你想要的。

PerformChanges<YourDbObject, AgentIdentification>(x => x.AgentIdentification, sNum, _db);
PerformChanges<YourDbObject, Agent>(x => x.Agent, sNum, _db);

private void PerformChanges<DbType,TCollection>(Func<DbType,DbSet<TCollection>> FetchDbSetLambda, int sNum, DbType your_db)
        {
            var aI = (from s in FetchDbSetLambda(your_db)
                      where s.SymetraNumber == sNum
                      select s);

            foreach (var record in aI)
                FetchDbSetLambda(your_db).DeleteObject(record);
        }
于 2013-01-22T21:14:55.740 回答