NealR
NealR

Reputation: 10709

Search with generic data types in ASP MVC/Entity Framework

Below is code I use in a WCF Service Reference I'm building using the Entity Framework. As you can see, right now I'm using the same code over and over again. Is there a syntax that will allow me to replace the entities with a generic type or another such method that would cut down on the amount of code being used?

        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();

Upvotes: 1

Views: 186

Answers (1)

Malcolm O'Hare
Malcolm O'Hare

Reputation: 5009

I believe this is what you want.

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

Upvotes: 1

Related Questions