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



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

我从Microsoft文档中找到了下面的片段。我想知道是否有任何方法可以使用EntityDataReader将整行读取到 Onject(此示例中的"联系人"(中,而不是将每个字段映射到每个属性?我的意思是,与其一一读取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();
}

最干净的选择是按照@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()

最新更新