1

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

1 Answer 1

1

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);
        }
Sign up to request clarification or add additional context in comments.

2 Comments

The 'FetchDbSetLambda' keyword seems to be causing an error. I get this message after doing mouse-over: 'Could not find an implementation of the query pattern for source type 'TCollection'. 'Where' not found.
My apologies, I had some errors in the method declaration. The Func<> type for TCollection should have been in an DbSet(assuming we are using EntityFramework). As well, the name of the int parameter was wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.