1

当我尝试强制转换为具有 Bar 属性的类 Foo 时遇到问题。Bar 类的属性与 Foo 类的属性同名:

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Bar Bar { get; set; }
}

public class Bar
{
    public int Id { get; set; }
    public string Name { get; set; }
}

数据库架构如下所示:

CREATE TABLE dbo.TB_Foo
(
    foo_Id INT PRIMARY KEY
    ,foo_Name NVARCHAR(20)
)
GO

CREATE TABLE dbo.TB_Bar
(
    bar_Id INT PRIMARY KEY
    ,bar_Name NVARCHAR(20)
    ,bar_FooId INT 

    ,FOREIGN KEY(bar_FooId) REFERENCES dbo.TB_Foo(foo_Id)
)
GO

样本数据:

INSERT INTO dbo.TB_Foo(foo_Id, foo_Name) 
    VALUES (1, 'Foo1'), (2, 'Foo2'), (3, 'Foo3')

INSERT INTO dbo.TB_Bar(bar_Id, bar_Name, bar_FooId) 
    VALUES (1, 'Bar1', 1), (2, 'Bar2', 2), (3, 'Bar3', 3)

当我尝试对对象使用 Simple.Data 强制转换时,出现异常:

“System.ArgumentException:已添加具有相同键的项目”

dynamic barAlias;

List<Foo> list = db.TB_Foo
    .All()
    .With(db.TB_Foo.TB_Bar.As("Bar"), out barAlias)
    .Select(
        // Columns for properties of class Foo
        db.TB_Foo.foo_Id.As("Id"),
        db.TB_Foo.foo_Name.As("Name"),

        // Columns for properties of class Bar
        barAlias.bar_Id.As("Id"),
        barAlias.bar_Name.As("Name") 
    )
    .ToList<Foo>();

有没有办法做到这一点?(对不起,我的英语不好)。

4

1 回答 1

1

这里的问题是 Simple.Data 使用自己的内部别名来处理 With 子句。这是我可以在下一次迭代中查看的内容,但现在显而易见的答案是重命名列,这样它们就不会以它们所在的表的名称作为前缀。如果表列的名称与属性,那么你不需要别名,一切都会工作。

无论如何,列前缀背后的想法是什么?

于 2014-05-24T10:11:39.750 回答