如何在带有私有构造函数的 class 中使用 iQueryable?
How can I use iQueryable in a class with a private constructor?
我刚开始学习 Linq,我正在尝试将数据库 table 映射到 class,但我无法使用私有构造函数来实现它。
我的代码:
namespace LinqTest
{
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
[Table(Name = "tblCity")]
public class City
{
private City()
{
}
[Column(IsPrimaryKey = true, Name = "CityId")]
public int Id { get; private set; }
[Column(Name = "CityName")]
public string Name { get; private set; }
public static List<City> GetList()
{
var dataContext = new DataContext(Database.ConnectionString());
var cities = dataContext.GetTable<City>();
var iQueryable =
from city in cities
select city;
return iQueryable.ToList();
}
}
}
我也试过映射到新实例:
var list = new List<City>();
foreach (var iCity in iQueryable)
{
var city = new City
{
Id = iCity.Id,
Name = iCity.Name
};
list.Add(city);
}
return list;
我该怎么做才能完成这项工作?我愿意接受其他方法。
谢谢
您不能在 foreach 中使用 iqueryable
对象。因为这只是一个查询。您必须使用 ToList()
获取对象。请试试这个:
var list = new List<City>();
foreach (var iCity in iQueryable.ToList())// return iqueryable to list
{
var city = new City
{
Id = iCity.Id,
Name = iCity.Name
};
list.Add(city);
}
return list;
或者您可以搜索automapper。一个例子 here
我刚开始学习 Linq,我正在尝试将数据库 table 映射到 class,但我无法使用私有构造函数来实现它。
我的代码:
namespace LinqTest
{
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
[Table(Name = "tblCity")]
public class City
{
private City()
{
}
[Column(IsPrimaryKey = true, Name = "CityId")]
public int Id { get; private set; }
[Column(Name = "CityName")]
public string Name { get; private set; }
public static List<City> GetList()
{
var dataContext = new DataContext(Database.ConnectionString());
var cities = dataContext.GetTable<City>();
var iQueryable =
from city in cities
select city;
return iQueryable.ToList();
}
}
}
我也试过映射到新实例:
var list = new List<City>();
foreach (var iCity in iQueryable)
{
var city = new City
{
Id = iCity.Id,
Name = iCity.Name
};
list.Add(city);
}
return list;
我该怎么做才能完成这项工作?我愿意接受其他方法。 谢谢
您不能在 foreach 中使用 iqueryable
对象。因为这只是一个查询。您必须使用 ToList()
获取对象。请试试这个:
var list = new List<City>();
foreach (var iCity in iQueryable.ToList())// return iqueryable to list
{
var city = new City
{
Id = iCity.Id,
Name = iCity.Name
};
list.Add(city);
}
return list;
或者您可以搜索automapper。一个例子 here