views:

110

answers:

2

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?

+1  A: 

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.

James Black
My controllers use the interfaces for the model, and translate those into ViewModel objects. I hear what you are saying on not using the LINQ model except in the data access/repository area, and mapping them into different classes. Using the interfaces has really given me a lot of flexibility for managing change in one area and having it not affect others.
blu
+1 though because its not a bad answer, just not what I am looking for right now.
blu
It just seems that uses interfaces for something that ideally is just a class of properties may be overkill, as you will define the properties in the interface, then in the class. I tend to useclass User { public String Name { get; set; }}So my class for the interface would be identical to the interface.
James Black
I appreciate your input, but am still looking for an answer to the original question.
blu
I ended up moving to this approach in general, thanks for the input.
blu
A: 

Dunno if this will suit, but perhaps using genrics might be an idea?

class FooRepository<T>
where T: class, IFoo, new() 
{
    // ...
    public void Add(T foo) 
    {
        db.Foos.InsertOnSubmit(foo);    
    }
}

And you can do something like this -

Foo bar = new Foo();
FooRepository<Foo> foo = new FooRepository<Foo>();
bar.Add(bar);

Or this...

Bar bar = new Bar(); //Bar implements IFoo
FooRepository<Bar> foo = new FooRepository<Bar>();
bar.Add(bar);

That way, T in FooRepository is actually a Foo (or a Bar), not an IFoo, so no casting is required, but the restriction in the where clause means that it must implement IFoo, which Foo (and Bar) does.

Frank Tzanabetis