使用 Linq-to-Sql 接口进行解耦
我正在将模型类重构为接口。模型类是使用 Linq-to-Sql 自动生成的。
class FooRepository
{
// ...
public void Add(IFoo foo)
{
db.Foos.InsertOnSubmit(foo);
}
}
InsertOnSubmit 方法采用 Foo 的实例,而不是 IFoo。我可以将实例内联转换为 (Foo) 并且这可以工作,但是有没有更干净的方法来做到这一点?
我已经在使用 StructureMap,我可以向 Add 方法添加一个属性来根据我的映射解析类型吗?
或者我可以重写任何模型类方法,或使用部分事件来完成此任务吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了将 DLINQ 模型与控制器分开,我倾向于不传递 LINQ 模型,而是使用控制器使用的不同模型,该模型在调用 DLINQ 方法之前传递到我的类中。
这样,即使数据库中可能有许多其他可用属性,我也可以在控制器中仅包含应用程序所需的属性。
这样,如果数据库结构发生变化,则只需更改 DAO 类(例如 FooRepository),其他所有内容都不会受到连锁反应。
我不知道您是否愿意做这样的事情,但这将是一个比使用我期望的接口更简单的设计。
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.
不知道这是否适合,但也许使用泛型可能是一个主意?
你可以做这样的事情 -
或者这样...
这样,FooRepository 中的 T 实际上是一个 Foo (或一个 Bar),而不是一个 IFoo,所以不需要强制转换,但是 where 子句中的限制意味着它必须实现 IFoo,这是 Foo(和 Bar)所做的。
Dunno if this will suit, but perhaps using genrics might be an idea?
And you can do something like this -
Or this...
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.