使用EntityDataReader从数据库中读取实体对象。

问题描述 投票:0回答:1

由于某些原因,我需要使用ADO.Net直接从数据库中读取实体对象。

我从下面的片段中找到了 微软文档. 我想知道是否有任何方法来读取整个行到一个Onject('contact'在这个例子中),使用 EntityDataReader 而不是将每个字段映射到每个属性?我的意思是说,与其读取 Contact.IdContact.Name 和其他字段逐一读取,有没有什么方法可以将一行读到一个对象中?

using (EntityConnection conn =
    new EntityConnection("name=AdventureWorksEntities"))
{
    conn.Open();

    string esqlQuery = @"SELECT VALUE contacts FROM
            AdventureWorksEntities.Contacts AS contacts
            WHERE contacts.ContactID == @id";

    // Create an EntityCommand.
    using (EntityCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = esqlQuery;
        EntityParameter param = new EntityParameter();
        param.ParameterName = "id";
        param.Value = 3;
        cmd.Parameters.Add(param);

        // Execute the command.
        using (EntityDataReader rdr =
            cmd.ExecuteReader(CommandBehavior.SequentialAccess))
        {
            // The result returned by this query contains
            // Address complex Types.
            while (rdr.Read())
            {
                // Display CustomerID
                Console.WriteLine("Contact ID: {0}",
                    rdr["ContactID"]);
                // Display Address information.
                DbDataRecord nestedRecord =
                    rdr["EmailPhoneComplexProperty"] as DbDataRecord;
                Console.WriteLine("Email and Phone Info:");
                for (int i = 0; i < nestedRecord.FieldCount; i++)
                {
                    Console.WriteLine("  " + nestedRecord.GetName(i) +
                        ": " + nestedRecord.GetValue(i));
                }
            }
        }
    }
    conn.Close();
}
c# entity-framework-6 ado.net sqldatareader
1个回答
1
投票

你最简单的选择是使用EntityFramework来执行你的查询,就像@herosuper所建议的那样。

在你的例子中,你需要做这样的事情。

EntityContext ctx = new EntityContext();
var contacts= ctx.Contacts
    .SqlQuery("SELECT * FROM AdventureWorksEntities.Contacts AS contacts" 
+ "WHERE contacts.ContactID =@id", new SqlParameter("@id", 3)).ToList();

从这里开始,你就可以:

var myvariable = contacts[0].ContactID;//zero is index of list. you can use foreach loop.
var mysecondvariable = contacts[0].EmailPhoneComplexProperty;

或者,你可以跳过整个SQL字符串,这样做。

EntityContext ctx = new EntityContext();
var contact= ctx.Contacts.Where(a=> a.ContactID ==3).ToList();

我假设查询返回的记录不止一条,否则你只需使用 FirstOrDefault() 而不是 Where()

© www.soinside.com 2019 - 2024. All rights reserved.