简体   繁体   English

DapperExtensions GetById 不返回 object

[英]DapperExtensions GetById not returning the object

I'm using DapperExtensions and the framework I'm using is .NET-Core.我正在使用 DapperExtensions,我正在使用的框架是 .NET-Core。

I have a base repository with the following:我有一个包含以下内容的基本存储库:

public T GetById(int id)
{
   using (SqlConnection sqlConnection = new SqlConnection(_dbConnection.ConnectionString))
   {
      return sqlConnection.Get<T>(id);
   }
}

I'm calling this method like so:我这样调用这个方法:

var skip = _skipRepository.GetById(id);

In my table I only have 3 records and as you can see I'm trying to grab a Skip by Id在我的表中,我只有 3 条记录,如您所见,我正在尝试按Id获取Skip

Here is my domain object:这是我的域 object:

public class Skip
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public decimal BasePrice { get; set; }

    public decimal PricePerDayAfter14Days { get; set; }

    public int Quantity { get; set; }
}

For some reason, the GetById throws an exception indicating that it expects 1 element but has got 3 elements.出于某种原因, GetById抛出一个异常,表明它需要 1 个元素,但有 3 个元素。

My database table has 3 records and so I started to dig deeper and run a SQL Profiler to what I found this query:我的数据库表有 3 条记录,所以我开始深入挖掘并运行 SQL Profiler 来查找我发现的这个查询:

SELECT [y_1].[Id] AS [c_0], [y_1].[Name] AS [c_1], [y_1].[Description] AS [c_2], [y_1].[BasePrice] AS [c_3], [y_1].[PricePerDayAfter14Days] AS [c_4], [y_1].[Quantity] AS [c_5] FROM [Skip] [y_1]

As you can see its not added a Where clause and I'm struggling to understand why.正如你所看到的,它没有添加 Where 子句,我很难理解为什么。

Does anyone know what I'm doing wrong?有谁知道我做错了什么?

You are mapping the primary key using [Key] attribute.您正在使用[Key]属性映射主键。 This mapping does not work with Dapper Extensions.此映射不适用于 Dapper Extensions。 You need to map something like below:您需要 map 如下所示:

public sealed class ProductMapper : ClassMapper<Product>
{
    public ProductMapper()
    {
        Schema("dbo");
        Table("Products");
        Map(x => x.Id).Key(KeyType.Guid);
        AutoMap();
    }
}

You also need to call SetMappingAssemblies at the startup of the project to apply these mappings.您还需要在项目启动时调用SetMappingAssemblies以应用这些映射。

Please refer to this answer to learn more about mappings in Dapper Extensions.请参阅答案以了解有关 Dapper Extensions 中映射的更多信息。

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

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