简体   繁体   中英

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 :

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

} 

I populate a class in my Global.asax file like so:

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. 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?)

It's returning IEnumerable<SitesVM> rather than 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

The SqlQuery() function is not returning a SitesVM object, it is a returning an enumeration of such objects (an IEnumerable ). There may be zero or more rows in the query result.

Use the First() method to get the first returned row. Note that this will throw an InvalidOperationException if the query returns no rows (the enumeration is empty).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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