使用 Dapper.net 的多重映射查询出现意外行为

发布于 2024-11-24 01:45:05 字数 1879 浏览 0 评论 0原文

我刚刚开始查看 Dapper.net,并且刚刚尝试了一些不同的查询,其中之一产生了我意想不到的奇怪结果。

我有 2 张桌子 - 照片PhotoCategories,其中与 CategoryID 相关

照片表

PhotoId (PK - int)  
CategoryId (FK - smallint)  
UserId (int)

PhotoCategories 表

CategoryId (PK - smallint)  
CategoryName (nvarchar(50))

我的 2 个课程:

public class Photo
{
    public int PhotoId { get; set; }
    public short CategoryId { get; set; }
    public int UserId { get; set; }
    public PhotoCategory PhotoCategory { get; set; }
}

public class PhotoCategory
{
    public short CategoryId { get; set; }
    public string CategoryName { get; set; }
{

我想使用多重映射返回 Photo 的实例,以及相关 PhotoCategory 的填充实例。

var sql = @"select p.*, c.* from Photos p inner 
            join PhotoCategories c 
            on p.CategoryID = c.CategoryID where p.PhotoID = @pid";

cn.Open();
var myPhoto = cn.Query<Photo, PhotoCategory, Photo>(sql, 
               (photo, photoCategory) => { photo.PhotoCategory = photoCategory; 
                                           return photo; }, 
               new { pid = photoID }, null, true, splitOn: "CategoryID").Single();

执行此操作时,并非所有属性都会被填充(尽管数据库表和我的对象中的名称相同)。

我注意到,如果我“选择 p.* 等”在我的 SQL 中,

我想从查询中返回 EXCLUDING p.CategoryId,然后所有内容都会被填充 (显然除了照片的 CategoryId我已从 select 语句中排除的对象)。

但我希望能够在查询中包含该字段,并拥有它,以及 SQL 中查询的所有其他字段, 我可以从我的 Photo 类中排除

CategoryId 属性,并在需要 ID 时始终使用 Photo.PhotoCategory.CategoryId

但在某些情况下我可能会 当我获得以下对象的实例时,不想填充 PhotoCategory 对象 照片对象。

有谁知道为什么会发生上述行为?这对 Dapper 来说正常吗?

I've only just started looking at Dapper.net and have just been experimenting with some different queries, one of which is producing weird results that i wouldn't expect.

I have 2 tables - Photos & PhotoCategories, of which are related on CategoryID

Photos Table

PhotoId (PK - int)  
CategoryId (FK - smallint)  
UserId (int)

PhotoCategories Table

CategoryId (PK - smallint)  
CategoryName (nvarchar(50))

My 2 classes:

public class Photo
{
    public int PhotoId { get; set; }
    public short CategoryId { get; set; }
    public int UserId { get; set; }
    public PhotoCategory PhotoCategory { get; set; }
}

public class PhotoCategory
{
    public short CategoryId { get; set; }
    public string CategoryName { get; set; }
{

I want to use multi-mapping to return an instance of Photo, with a populated instance of the related PhotoCategory.

var sql = @"select p.*, c.* from Photos p inner 
            join PhotoCategories c 
            on p.CategoryID = c.CategoryID where p.PhotoID = @pid";

cn.Open();
var myPhoto = cn.Query<Photo, PhotoCategory, Photo>(sql, 
               (photo, photoCategory) => { photo.PhotoCategory = photoCategory; 
                                           return photo; }, 
               new { pid = photoID }, null, true, splitOn: "CategoryID").Single();

When this is executed, not all of the properties are getting populated (despite the same names between the DB table and in my objects.

I noticed that if I don't 'select p.* etc.' in my SQL, and instead.

I explicitly state the fields.

I want to return EXCLUDING p.CategoryId from the query, then everything gets populated (except obviously the CategoryId against the Photo object which I've excluded from the select statement).

But i would expect to be able to include that field in the query, and have it, as well as all the other fields queried within the SQL, to get populated.

I could just exclude the CategoryId property from my Photo class, and always use Photo.PhotoCategory.CategoryId when i need the ID.

But in some cases I might not want to populate the PhotoCategory object when I get an instance of
the Photo object.

Does anyone know why the above behavior is happening? Is this normal for Dapper?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无所的.畏惧 2024-12-01 01:45:05

我刚刚为此提交了一个修复程序:

    class Foo1 
    {
        public int Id;
        public int BarId { get; set; }
    }

    class Bar1
    {
        public int BarId;
        public string Name { get; set; }
    }

    public void TestMultiMapperIsNotConfusedWithUnorderedCols()
    {

        var result = connection.Query<Foo1,Bar1,
                      Tuple<Foo1,Bar1>>(
                         "select 1 as Id, 2 as BarId, 3 as BarId, 'a' as Name",
                         (f,b) => Tuple.Create(f,b), splitOn: "BarId")
                         .First();

        result.Item1.Id.IsEqualTo(1);
        result.Item1.BarId.IsEqualTo(2);
        result.Item2.BarId.IsEqualTo(3);
        result.Item2.Name.IsEqualTo("a");

    }

如果 first 类型中有一个字段,而该字段恰好也在 second 类型中,则多映射器会感到困惑。 .AND ... 被用作分割点。

为了克服现在的短小精悍,允许 Id 字段显示在第一种类型中的任何位置。举例说明。

假设我们有:

classes: A{Id,FooId} B{FooId,Name}
splitOn: "FooId"
data: Id, FooId, FooId, Name

旧的拆分方法没有考虑它所映射的实际底层类型。所以...它映射了 Id =>; AFooId, FooId, Name => B

新方法知道A中的props和字段。当它第一次在流中遇到 FooId 时,它不会启动分割,因为它知道 A 有一个名为 FooId 的属性,需要将其映射后,下次它看到 FooId 时就会分裂,从而产生预期的结果。

I just committed a fix for this:

    class Foo1 
    {
        public int Id;
        public int BarId { get; set; }
    }

    class Bar1
    {
        public int BarId;
        public string Name { get; set; }
    }

    public void TestMultiMapperIsNotConfusedWithUnorderedCols()
    {

        var result = connection.Query<Foo1,Bar1,
                      Tuple<Foo1,Bar1>>(
                         "select 1 as Id, 2 as BarId, 3 as BarId, 'a' as Name",
                         (f,b) => Tuple.Create(f,b), splitOn: "BarId")
                         .First();

        result.Item1.Id.IsEqualTo(1);
        result.Item1.BarId.IsEqualTo(2);
        result.Item2.BarId.IsEqualTo(3);
        result.Item2.Name.IsEqualTo("a");

    }

The multi-mapper was getting confused if there was a field in the first type, that also happened to be in the second type ... AND ... was used as a split point.

To overcome now dapper allow for the Id field to show up anywhere in the first type. To illustrate.

Say we have:

classes: A{Id,FooId} B{FooId,Name}
splitOn: "FooId"
data: Id, FooId, FooId, Name

The old method of splitting was taking no account of the actual underlying type it was mapping. So ... it mapped Id => A and FooId, FooId, Name => B

The new method is aware of the props and fields in A. When it first encounters FooId in the stream it does not start a split, since it knows that A has a property called FooId which needs to be mapped, next time it sees FooId it will split, resulting in the expected results.

初心 2024-12-01 01:45:05

我也有类似的问题。这是因为子级和父级对于要分割的字段具有相同的名称。例如,以下示例有效:

class Program
{
    static void Main(string[] args)
    {
        var createSql = @"
            create table #Users (UserId int, Name varchar(20))
            create table #Posts (Id int, OwnerId int, Content varchar(20))

            insert #Users values(99, 'Sam')
            insert #Users values(2, 'I am')

            insert #Posts values(1, 99, 'Sams Post1')
            insert #Posts values(2, 99, 'Sams Post2')
            insert #Posts values(3, null, 'no ones post')
        ";

        var sql =
        @"select * from #Posts p 
        left join #Users u on u.UserId = p.OwnerId 
        Order by p.Id";

        using (var connection = new SqlConnection(@"CONNECTION STRING HERE"))
        {
            connection.Open();
            connection.Execute(createSql);

            var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post; }, splitOn: "UserId");
            var apost = data.First();

            apost.Content = apost.Content;
            connection.Execute("drop table #Users drop table #Posts");
        }
    }
}

class User
{
    public int UserId { get; set; }
    public string Name { get; set; }
}
class Post
{
    public int Id { get; set; }
    public int OwnerId { get; set; }
    public User Owner { get; set; }
    public string Content { get; set; }
}

但以下示例无效,因为两个表和两个对象中都使用了“UserId”。

class Program
{
    static void Main(string[] args)
    {
        var createSql = @"
            create table #Users (UserId int, Name varchar(20))
            create table #Posts (Id int, UserId int, Content varchar(20))

            insert #Users values(99, 'Sam')
            insert #Users values(2, 'I am')

            insert #Posts values(1, 99, 'Sams Post1')
            insert #Posts values(2, 99, 'Sams Post2')
            insert #Posts values(3, null, 'no ones post')
        ";

        var sql =
        @"select * from #Posts p 
        left join #Users u on u.UserId = p.UserId 
        Order by p.Id";

        using (var connection = new SqlConnection(@"CONNECTION STRING HERE"))
        {
            connection.Open();
            connection.Execute(createSql);

            var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post; }, splitOn: "UserId");
            var apost = data.First();

            apost.Content = apost.Content;
            connection.Execute("drop table #Users drop table #Posts");
        }
    }
}

class User
{
    public int UserId { get; set; }
    public string Name { get; set; }
}
class Post
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public User Owner { get; set; }
    public string Content { get; set; }
}

在这种情况下,Dapper 的映射似乎变得非常混乱。认为这描述了问题,但是我们可以采用解决方案/解决方法吗(抛开 OO 设计决策)?

I'm having a similar problem. It's to do with the fact that both the child and the parent have the same name for the field that is being split on. The following for example works:

class Program
{
    static void Main(string[] args)
    {
        var createSql = @"
            create table #Users (UserId int, Name varchar(20))
            create table #Posts (Id int, OwnerId int, Content varchar(20))

            insert #Users values(99, 'Sam')
            insert #Users values(2, 'I am')

            insert #Posts values(1, 99, 'Sams Post1')
            insert #Posts values(2, 99, 'Sams Post2')
            insert #Posts values(3, null, 'no ones post')
        ";

        var sql =
        @"select * from #Posts p 
        left join #Users u on u.UserId = p.OwnerId 
        Order by p.Id";

        using (var connection = new SqlConnection(@"CONNECTION STRING HERE"))
        {
            connection.Open();
            connection.Execute(createSql);

            var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post; }, splitOn: "UserId");
            var apost = data.First();

            apost.Content = apost.Content;
            connection.Execute("drop table #Users drop table #Posts");
        }
    }
}

class User
{
    public int UserId { get; set; }
    public string Name { get; set; }
}
class Post
{
    public int Id { get; set; }
    public int OwnerId { get; set; }
    public User Owner { get; set; }
    public string Content { get; set; }
}

But the following does not because "UserId" is used in both tables and both objects.

class Program
{
    static void Main(string[] args)
    {
        var createSql = @"
            create table #Users (UserId int, Name varchar(20))
            create table #Posts (Id int, UserId int, Content varchar(20))

            insert #Users values(99, 'Sam')
            insert #Users values(2, 'I am')

            insert #Posts values(1, 99, 'Sams Post1')
            insert #Posts values(2, 99, 'Sams Post2')
            insert #Posts values(3, null, 'no ones post')
        ";

        var sql =
        @"select * from #Posts p 
        left join #Users u on u.UserId = p.UserId 
        Order by p.Id";

        using (var connection = new SqlConnection(@"CONNECTION STRING HERE"))
        {
            connection.Open();
            connection.Execute(createSql);

            var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post; }, splitOn: "UserId");
            var apost = data.First();

            apost.Content = apost.Content;
            connection.Execute("drop table #Users drop table #Posts");
        }
    }
}

class User
{
    public int UserId { get; set; }
    public string Name { get; set; }
}
class Post
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public User Owner { get; set; }
    public string Content { get; set; }
}

Dapper's mapping seems to get very confused in this scenario. Think this describes the issue but is there a solution / workaround we can employ (OO design decisions aside)?

幸福不弃 2024-12-01 01:45:05

我知道这个问题已经很老了,但我想我可以节省某人 2 分钟的时间,并给出明显的答案:只需从一个表中别名一个 id:

即:

SELECT
    user.Name, user.Email, user.AddressId As id, address.*
FROM 
    User user
    Join Address address
    ON user.AddressId = address.AddressId

I know this question is old but thought I would save someone 2 minutes with the obvious answer to this: Just alias one id from one table:

ie:

SELECT
    user.Name, user.Email, user.AddressId As id, address.*
FROM 
    User user
    Join Address address
    ON user.AddressId = address.AddressId
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文