C# LINQ 查询报错:指定的转换无效
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Dynamic; using System.Linq; using System.Runtime.CompilerServices; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Xml; using System.Runtime.Remoting.Contexts; namespace ConsoleApp3_Test { internal class Aa { static void Main(string[] args) { DataContext dataContext = new DataContext("server=192.168.1.1,12345;database=test;uid=sa;pwd=111"); Table<User> Users=dataContext.GetTable<User>(); User query = (from user in Users where user.name.Contains("王") select user ). First(); Console.WriteLine(query.name); } } [Table (Name = "c_user")] public class User { [Column(Name = "userid",IsPrimaryKey =true)] public int ID; //此处的字段类型错误,数据库中该字段类型为varchar [Column (Name = "username")] public string name; } }
原因:
实体类的字段(ID)的类型与数据库中的类型不一致。实体类的ID类型为int,数据库中的类型为varchar。将实体类中ID字段类型改为string 即可。