日期:2014-05-20  浏览次数:20926 次

提示指定的转换无效。。。
class Northwind : DataContext
  {
  public Table<Depart> T_Dept;
  public Northwind(string conn) : base(conn) { }
  }
  [Table(Name="T_Depart")]
  public class Depart
  {
  [Column(IsPrimaryKey = true, IsDbGenerated = true)]
  public int DeptId { set; get; }

  [Column(Name="DeptManId")]
  public int DeptManId { set; get; }
  [Column]
  public string DeptName { set; get; }
  [Column]
  public string DeptTel { set; get; }
  [Column]
  public string DeptFax { set; get; }

  //public Table<Employee> emps { set; get; }
  }
  static void Main(string[] args)
  {
  Northwind nw = new Northwind(@"*****");
  var select = (from td in nw.T_Dept
  where td.DeptId == 1
  select new
  {
  DeptId = td.DeptId,
  DeptFax = td.DeptFax,
  DeptTel = td.DeptTel,
  DeptName = td.DeptName,
  DeptManId = td.DeptManId
  });
  Depart dept = nw.T_Dept.First();
  Console.ReadKey();
  }


Depart dept = nw.T_Dept.First();提示指定的转换无效。。。
请问怎么解决????

------解决方案--------------------
C# code
Northwind nw = new Northwind(@"*****");
  var select = (from td in nw.T_Dept
  where td.DeptId == 1
  select new Depart  //注意此处
  {
  DeptId = td.DeptId,
  DeptFax = td.DeptFax,
  DeptTel = td.DeptTel,
  DeptName = td.DeptName,
  DeptManId = td.DeptManId
  }).FirstOrDefault();
  Depart dept = (select ==null? new Depart(): select);
  Console.ReadKey();

------解决方案--------------------
http://www.cnblogs.com/JeffreyZhao/archive/2008/02/19/using-translate-method-and-modify-command-text-before-query-in-linq-to-sql.html

C# code

Northwind nw = new Northwind(@"*****");
  var select = (from td in nw.T_Dept
  where td.DeptId == 1
  select new  
  {
  DeptId = td.DeptId,
  DeptFax = td.DeptFax,
  DeptTel = td.DeptTel,
  DeptName = td.DeptName,
  DeptManId = td.DeptManId
  }).FirstOrDefault();

 using (dataContext.Connection)
    {
         Depart dept =nw.ExecuteQuery<Depart>(query, true).FirstOrDefault();
    }

------解决方案--------------------
探讨
class Northwind : DataContext
{
public Table<Depart> T_Dept;
public Northwind(string conn) : base(conn) { }
}
[Table(Name="T_Depart")]
public class Depart
……