简体   繁体   English

C#dapper映射到接口

[英]C# dapper map to interface

Can i use C# dapper to do something like this: 我可以使用C#dapper做这样的事情:

IFoo bar = _dbConnection.Query<IFoo>("My query there");

Now I can't do it, due to not impelemented default parameterless constructor. 现在我不能这样做,因为没有必要的默认无参数构造函数。

Is there some trick to honor gods of SOLID (especially spirits of Liskov Substitution Principle) or should i leave it as it is and map my data not to IFoo but to Foo? 是否有一些技巧来尊重SOLID的神(特别是Liskov替换原则的精神)或者我应该保留它并将我的数据映射到IFoo而不是Foo?

I'm really worrying about respecting these SOLID stuff, but still don't know where i should do it, so looking for an advice for this concrete situation. 我真的很担心尊重这些SOLID的东西,但仍然不知道我应该在哪里做,所以寻找这个具体情况的建议。

You need a concrete implementation of your class to instantiate. 您需要实例化类的具体实现。 Internally, it has to do a create a new object. 在内部,它必须创建一个新对象。 You can't create a new instance of an interface: 您无法创建接口的新实例:

var foo = new IFoo(); // This won't build!

You can still cast your result to an interface, but you need a concrete type to build from the database. 您仍然可以将结果转换为接口,但是您需要从数据库构建具体类型。

IEnumerable<IFoo> foo = _dbConnection.Query<Foo>("My query there");

One way to organise repository is to use private class objects for querying, but expose results as public interfaces. 组织存储库的一种方法是使用私有类对象进行查询,但将结果公开为公共接口。

Pulbic Model: Pulbic模型:

namespace MyProject.Foo.Model
{
    public interface IFoo
    {
        string Property1 { get; set; }
        string Property2 { get; set; }
    }

    public interface IFooRepository
    {
        IEnumerbale<IFoo> GetFoos();
    }
}

Query implementation with private class: 使用私有类查询实现:

namespace MyProject.Foo.Repositories
{
    public class FooRepository: IFooRepository
    {
        private class Foo: IFoo
        {
            public string Property1 { get; set; }
            public string Property2 { get; set; }
        }

        public IEnumerbale<IFoo> GetFoos()
        {
            IEnumerable<IFoo> foo = _dbConnection.Query<Foo>("My query there");
            return foo;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM