【问题标题】:EF ComplexType fields orderEF ComplexType 字段顺序
【发布时间】:2015-05-04 23:30:00
【问题描述】:

我开始使用 C# 在 EF 中工作我正在做一个示例,我只需执行一个 SP,我需要检索到一个 DataGridView。

我添加了 SP 并创建了一个复杂类型,我的 SP 看起来像这样

select ProductId, ProductName, S.SupplierID, S.CompanyName, 
       C.CategoryID, C.CategoryName, UnitPrice
from dbo.Products P
inner join Suppliers S on S.SupplierID = P.SupplierID
inner join Categories C on C.CategoryID = P.CategoryID

但是,当我将数据检索到 DataGridView 时,Complex 类型以不同的顺序显示结果,实际上它是这样显示的

ProductName, SupplierID, CategoryID (...)

所以我想知道是否有机会修改我的 complexType 并按照我的 SP 的相同顺序获取输出?

【问题讨论】:

  • 如果您使用 EF,为什么需要存储过程?直接从 LINQ to Entities 查询数据库。
  • 嗯,我想可能是因为在我的工作(银行)中我们仍然使用 SP,因为内部安全策略我们不能只在代码中编写数据库逻辑。所以谢谢你的建议,但这不是我要的。最好的问候。
  • 好的,然后映射存储的 proc 输出或创建一个视图(如果允许)。见msdn.microsoft.com/en-us/library/vstudio/…stackoverflow.com/questions/12833531/…
  • 无论如何愚蠢的政策,安全“工程师”的专业发展使这个决定在 1998 年的某个地方停止,
  • 此外,您可能还想尝试其他 ORM,例如 Dapper,因为将 EF 与 SP 结合使用会失去它的最大功能和特性。

标签: c# winforms entity-framework datagridview


【解决方案1】:

在实体框架中创建和映射类型:

class Product
{
    public Guid ProductId { get; set; }
    public string ProductName { get; set; }
    public double UnitPrice { get; set; }
    public Supplier Supplier { get; set; }
    public Category Category { get; set; }
}

class Supplier
{
    public Guid SupplierID { get; set; }
    public string SupplierName { get; set; }
}

class Category 
{
    public Guid CategoryID { get; set; }
    public string CategoryName { get; set; }
}

然后查询你的数据库:

var q = from p in db.Products
        select new
        {
            p.ProductId, p.ProductName, p.UnitPrice,
            p.Supplier.SupplierID, p.Supplier.CompanyName, 
            p.Category.CategoryID, p.Category.CategoryName, 
        };

然后将其绑定到控件上:

dataGridView.DataSource = q.ToArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2012-11-08
    • 2020-06-13
    相关资源
    最近更新 更多