Business layer handling Linq-objects without knowi

2019-07-26 10:08发布

I am refactoring my application to be less dependent on the data source (at the moment I am using Linq To Sql). But I like the nice way that Linq To Sql generates my classes out of my database and the way it tracks changes.

If this was not Linq I would just wrap the class with an interface and then let my business layer depend on that interface. However, I cannot do this with linq.

So lets say I have a repository IFooRepository where Foos is a table in the database and Linq has generated the class Foo for me. If I wouldn't bother about dependencies I would just return the linq object Foo. But my Business Logic layer has no clue of my Linq layer so I cannot inject those objects into my BLL. And as my Linq objects cannot implement any interface I cannot have any functions in the IFooRepository returning an IFoo implementation.

So, what I want is just for my BLL to handle the Linq objects but without knowing it so that my Linq Layer will track the changes of the BLL. Is this possible? I am thinking of just having a class inherit from the Linq object and then use that for passing around. Would that be valid?

2条回答
Animai°情兽
2楼-- · 2019-07-26 10:41

This is certainly possible, especially with LINQ to SQL. You need to do two things here:

  1. Use POCO objects (see here and here for T4 automation).
  2. Hide the DataContext behind an abstraction.

Good luck.

查看更多
祖国的老花朵
3楼-- · 2019-07-26 10:44

Your LINQ-to-SQL entities can implement interfaces, and you can add any functionality to them that you like. The generated entities are partial classes, so you can do something akin to this in another file, as long as it's part of your LINQ-to-SQL assembly:

public partial class YourEntityType : IInterfaceName
{
    // your implementation
}

You just need to define the contracts in another assembly that is referenced both by the LINQ-to-SQL assembly and the business logic assembly.

查看更多
登录 后发表回答