我真的不了解这一点,因为我只涉猎MVC和C#。如果术语错误或令人困惑,我深表歉意,我将尽力回答问题。我有几个这样的模型:
public class DataSharingModels
{
public string ReferenceID { get; set; }
public NBTC NBTCGroup { get; set; }
public Contractors ContractorsGroup { get; set; }
public Coordinators CoordinatorsGroup { get; set; }
public NGO NGOGroup { get; set; }
public Public PublicGroup { get; set; }
public SelectList FA_RA_List { get; set; }
}
public class NBTC
{
public String NBTC_FA_Centroid { get; set; }
public String NBTC_FA_Bound { get; set; }
public String NBTC_RA_Centroid { get; set; }
//more properties...
}
DataSharingModels
类包含public NBTC NBTCGroup
属性。它不是public List<NBTC> NBTCGroup
,因为每个被命中的控制器实例只会产生一个。
现在在我的控制器中,我有一个LINQ语句,用于选择新的NBTC类:
var nbtcVals = (from ds in db.SharingPermissions
where ds.FocalRefID.ToString() == ReferenceID
&& ds.ShareGroup == "NBTC"
select new NBTC
{
NBTC_FA_Centroid = ds.CIP_FA_Centroid,
NBTC_FA_Bound = ds.CIP_FA_Boundary,
NBTC_RA_Centroid = ds.CIP_RA_Centroid,
//more properties...
});
我要出错的地方是要将其添加到我的DataSharingModels
模型中。我以为nbtcVals
类型是NBTC,但是它是IQueryable <##。Models.NBTC>。我知道我可以这样做,但是似乎多余:
DataSharingModels dsm = new DataSharingModels();
if (nbtcVals.Any())
{
foreach (var i in nbtcVals)
{
dsm.NBTCGroup.NBTC_FA_Centroid = i.NBTC_FA_Centroid;
dsm.NBTCGroup.NBTC_FA_Boundary = i.NBTC_FA_Bound;
dsm.NBTCGroup.NBTC_RA_Centroid = i.NBTC_RA_Centroid;
//more properties...
}
}
更直接的方法是什么?必须有一个。我以为我也可以在LINQ查询中返回匿名类型,然后像foreach
一样在dsm.NBTCGroup.NBTC_RA_Centroid = i.NBTC_RA_Centroid
中分配每个属性,但这似乎与其他方法相同。
答案 0 :(得分:0)
var nbtcgroup = (from ds in db.SharingPermissions
where ds.FocalRefID.ToString() == ReferenceID
&& ds.ShareGroup == "NBTC"
select new NBTC
{
NBTC_FA_Centroid = ds.CIP_FA_Centroid,
NBTC_FA_Bound = ds.CIP_FA_Boundary,
NBTC_RA_Centroid = ds.CIP_RA_Centroid,
//more properties...
})
.OrderByDescending(n => n.Id) // or some other property that could identify sorting
.FirstOrDefault();
这是SQL的翻译版本(LIMIT或TOP,取决于后端)。