简体   繁体   English

从C#中的类对象获取属性

[英]Get property from class object in C#

I need to get the values of three properties from a class which I am populating from a stored procedure but don't know how. 我需要从存储过程中填充的一个类中获取三个属性的值,但不知道如何。

my viewModel : 我的viewModel:

public class SitesVM
{
    public int ID { get; set; }
    public string SiteName { get; set; }

} 

I populate a class in my Global.asax file like so: 我在Global.asax文件中填充一个类,如下所示:

string siteIpAddress = "67.46.255.255";  //HardCoded for testing
var site = context.Database.SqlQuery<SitesVM>("spSelect_SiteByIp", siteIpAddress);

The site is populated with the correct data, I can see it from the Locals debug screen, but I don't know how to retrieve the ID and SiteName into a variables. 该站点填充了正确的数据,我可以从Locals调试屏幕中看到它,但是我不知道如何将ID和SiteName检索到变量中。 I tried the following 我尝试了以下

var siteID = site.ID; //

but I get this build error: 但是我得到这个构建错误:

'System.Collections.Generic.IEnumerable' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?) 'System.Collections.Generic.IEnumerable'不包含'ID'的定义,并且找不到扩展方法'ID'接受类型为'System.Collections.Generic.IEnumerable'的第一个参数(您是否缺少using指令?或装配参考?)

It's returning IEnumerable<SitesVM> rather than SitesVM 它返回IEnumerable<SitesVM>而不是SitesVM

If you just want one result and you're sure there's only one, you could try: 如果您只想要一个结果并且确定只有一个结果,则可以尝试:

site.Single().ID;

This will return the ID of the single member of the sequence, and will throw an exception if there are zero or >1 results 这将返回序列中单个成员的ID,如果结果为零或> 1,则将引发异常。

The SqlQuery() function is not returning a SitesVM object, it is a returning an enumeration of such objects (an IEnumerable ). SqlQuery()函数不返回SitesVM对象,而是返回此类对象的枚举( IEnumerable )。 There may be zero or more rows in the query result. 查询结果中可能有零行或更多行。

Use the First() method to get the first returned row. 使用First()方法获取返回的第一行。 Note that this will throw an InvalidOperationException if the query returns no rows (the enumeration is empty). 请注意,如果查询不返回任何行(枚举为空),这将引发InvalidOperationException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM