使用Linq从数据库填充对象

本文关键字:填充 对象 数据库 Linq 使用 | 更新日期: 2023-09-27 18:07:21

我使用Entity Framework连接到数据库。现在,我想用Linq

为接收到的数据创建一个List<Object>

所以,我有:

var listOfSettings = new List<AppSetting>();
var query = from appSetting in AppSettings
            where appSetting.AppConfigID == appConfigId
            select new AppSetting()
            {
                AppSettingID = Int16.Parse(appSetting.AppSettingID),
                ...
            };

如何将AppSetting Object添加到Settings的List中?

使用Linq从数据库填充对象

List<AppSetting> listOfSettings = (from appSetting in AppSettings
                                  where appSetting.AppConfigID == appConfigId
                                  select new AppSetting()
                                  {
                                      AppSettingID = Int16.Parse(appSetting.Name),
                                      ...
                                  }).ToList();

最后,我不得不这样做:

var query = (AppSettings.Select(appSetting => new
            {
                AppSettingID = appSetting.AppSettingID,
                ...
            }).Where(appSetting => appSetting.AppConfigID == appConfigId)).ToList();
            listOfAppSettings.AddRange(query.Select(setting => new AppSetting()
            {
                AppSettingID = setting.AppSettingID, 
                ...
            }));