【问题标题】:Using Linq with existing Objects将 Linq 与现有对象一起使用
【发布时间】:2011-08-20 22:44:46
【问题描述】:

我的系统有这个模式DAO->Objects->facade->View

所以我有一个 DAO 来查询数据库和实例化对象,这个对象只有属性(只是一个容器/实体),我想在 DAO 部分使用 LINQ,但我不知道如何传递我的对象,因为 LINQ 生成每桌 1 个。

namespace ykpObjects.Objects
{
public class Customer
    {
        public string name { get; set; }
        public Cidade()
        {
            cidadeID = 0;
        }
    }
}

namespace ykpData.Components.MSSQL
{

    public class CustomerDC : DataComponentCM, ICustomerDC
    {

        Customer ICustomerDC.RecuperaPorID(int CustomerID)
        {
            Customer Customer = new Customer();

            using (MDDataContext omd = new MDDataContext(base.PreencherConexao()))
            {
                sp_mkp_Customer_SelectByIDResult result = omd.sp_mkp_Customer_SelectByID(CustomerID).SingleOrDefault();
                if (result == null)
                    return null;

                Customer.name = result.name;


                return Customer;
            }
        }
    }
}

我使用 DAO 调用 sprocs,所以我得到 sproc 结果并实例化 Customer 的一个对象,并将其传递给控制,现在我想更改为 linq,但我不想更改所有对象结构以最小化影响。

有什么建议吗?

【问题讨论】:

  • 你设计的Objects 部分对我来说没有任何意义。请详细说明。
  • 请澄清您的问题。
  • 我使用 DAO 调用 sprocs,所以我得到了 sproc 结果并实例化了 Customer 的一个对象,例如,并将其传递给控制,现在我想更改为 linq,但我不想更改所有对象结构尽量减少影响。

标签: c# linq-to-sql entity dao


【解决方案1】:

我不确定您在当前设置中谈论的是什么,但我认为您是在问如何通过 Linq to SQL 重用您当前拥有的对象,而不是从 dbml 文件生成新对象.我说的对吗?

如果是这样,您有几个选择。您可以使用属性来装饰现有对象,以便使用 L2S 填充它们,或者您可以创建映射文件。

这里有一些信息:http://www.sidarok.com/web/blog/content/2008/10/14/achieving-poco-s-in-linq-to-sql.html

我使用带有属性的 Linq to SQL 来实现“代码优先”的解决方案,这是一个示例类:

[Table(Name = "Countries")]    
public class Country
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int CountryId { get; set; }

    [Column]
    public string iso2 { get; set; }

    [Column]
    public string iso3 { get; set; }

    [Column]
    public string name_en { get; set; }
}

要使用这个对象:

var context = new DataContext(ConnectionString);
var data = context.GetTable<Country>().Where(c => c.CountryId == 1);

【讨论】:

  • 完全正确!,还有一个问题,我如何为这些对象设置数据库?
猜你喜欢
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-24
相关资源
最近更新 更多