Search code examples
c#interfacestructuremapdecoupling

Using interfaces with Linq-to-Sql for decoupling


I am re-factoring a model class into an interface. The model class is auto-generated with Linq-to-Sql.

class FooRepository 
{
    // ...
    public void Add(IFoo foo) 
    {
        db.Foos.InsertOnSubmit(foo);    
    }
}

The InsertOnSubmit method takes an instance of Foo, not an IFoo. I can cast the instance inline to (Foo) and this works, but is there a cleaner way to do this?

I am already using StructureMap, can I add an attribute to the Add method to resolve the type based on my mappings?

Or can I override any of the model classes methods, or use the partial events to accomplish this?


Solution

  • In order to separate the DLINQ model from the controller I tend not to pass the LINQ model around, but have a different model that is used by the controller, that is passed into my class before calling the DLINQ methods.

    This way I can have in my controller just the properties needed by the application, even though there may be many other properties available in the database.

    This way, should the database structure change only the DAO class, such as FooRepository, has to change, everything else is protected from the ripple effect.

    I don't know if you would want to do something like this but it would be a simpler design than using Interfaces I expect.