码迷,mamicode.com
首页 > 数据库 > 详细

EntityFramework执行SQL语句

时间:2015-10-08 23:00:41      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

在EF中执行Sql语句。

using (var context = new EFRecipesEntities())
{
   string sql = @"insert into Chapter3.Payment(Amount, Vendor)
                     values (@Amount, @Vendor)";
   var args = new DbParameter[] {
                   new SqlParameter { ParameterName = "Amount", Value = 99.97M},
                   new SqlParameter { ParameterName = "Vendor", Value="Ace Plumbing"}
                 };
   int rowCount = context.ExecuteStoreCommand(sql, args);
}
using (var context = new EFRecipesEntities())
{
   string sql = "select * from Chapter3.Student where Degree = @Major";
   var args = new DbParameter[] {
                  new SqlParameter {ParameterName = "Major", Value = "Masters"}};
   var students = context.ExecuteStoreQuery<Student>(sql, args);
   Console.WriteLine("Students...");
   foreach (var student in students)
   {
     Console.WriteLine("{0} {1} is working on a {2} degree",
   student.FirstName, student.LastName, student.Degree);
  }
}
using (var conn = new EntityConnection("name=EFRecipesEntities"))
{
    var cmd = conn.CreateCommand();
    conn.Open();
    cmd.CommandText = @"select c.Name, C.Email from
                                  EFRecipesEntities.Customers as c";
    using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
     {
       while (reader.Read())
           {
               Console.WriteLine("{0}‘s email is: {1}",
                                   reader.GetString(0), reader.GetString(1));
          }
    }
}

 

1.sql = "select * from Payment where Vendor= @vendor";之所以能写成select *是因为Payment对象的属性和表的字段命名完全一致,如果不一致的话,需要将表字段取别名,别名需是对象映射的属性名称。

2.如果sql语句返回的列少于(具体化)实体的属性的个数,那么EF在具体化的时候将抛出一个异常如下图,因此将需要缺少的列补上一些没有意义的值,以保证在具体乎的时候不会报错:eg 如图1,如果sql=”select PaymentId ,Amount from Payment ” 这样使用context.ExecuteStoreQuery<Payment >(sql, args);那么会报异常,因此需要将Vendor 列补上 。正确的sql=”select PaymentId ,Amount, null as Vendor from Payment”。

3.如果sql 返回的列 多余具体化的实体属性的个数,那么EF将会忽视多出的列。

EntityFramework执行SQL语句

标签:

原文地址:http://www.cnblogs.com/superfeeling/p/4862475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!