I've got a handful of products, any, all, or none of which may be associated with a specific submission. All 7 products are subclasses of the class Product. I need to store all the products associated with a submission, and then retrieve them and their field data on my presentation layer. I've been using a List<Product>
, and List<object>
, but when I use the OfType<EPL(specific subclass)>
, I throw an error saying that I can't implicitly convert systems.generic.IEnumerable<EPL>
to type 'Product'. I've tried to cast, but to no avail.
When I use prodlist.OfType<EPL>();
there are no errors, but when I try and store that in an instance of EPL "tempEpl", I get the aforementioned cast-related error. What gives? Code below.
ProductService pserv = new ProductService();
IList<object> prodlist = pserv.getProductById(x);
EPL tempEpl = new EPL();
if ((prodlist.OfType<EPL>()) != null)
{
tempEpl = prodlist.OfType<EPL>(); // this throws a conversion error.
}
the Data layer
List<object> TempProdList = new List<object>();
conn.Open();
SqlCommand EplCmd = new SqlCommand(EPLQuery, conn);
SqlDataReader EplRead = null;
EplRead = EplCmd.ExecuteReader();
EPL TempEpl = new EPL();
if (EplRead.Read())
{
TempEpl.Entity1 = EplRead.GetString(0);
TempEpl.Employees1 = EplRead.GetInt32(1);
TempEpl.CA1 = EplRead.GetInt32(2);
TempEpl.MI1 = EplRead.GetInt32(3);
TempEpl.NY1 = EplRead.GetInt32(4);
TempEpl.NJ1 = EplRead.GetInt32(5);
TempEpl.PrimEx1 = EplRead.GetInt32(6);
TempEpl.EplLim1 = EplRead.GetInt32(7);
TempEpl.E开发者_如何学PythonplSir1 = EplRead.GetInt32(8);
TempEpl.Premium1 = EplRead.GetInt32(9);
TempEpl.Wage1 = EplRead.GetInt32(10);
TempEpl.Sublim1 = EplRead.GetInt32(11);
TempProdList.Add(TempEpl);
}
This code makes no sense:
Product tempEpl = new EPL();
if ((prodlist.OfType<EPL>()) != null)
{
prodlist.OfType<EPL>();
}
- It's unclear why you're creating a new
EPL()
to start with OfType()
will never return null - it returns a sequence, which may be empty- Calling
OfType()
won't do anything useful on its own, as per the body of yourif
statement
It's important to understand that OfType()
returns a sequence, not a single item. I suspect that's what you were missing before.
I suspect you want:
Product tempEpl = prodList.OfType<EPL>().FirstOrDefault();
This will assign a value of null
to tempEpl
if there are no elements of type EPL
in prodList
, or the first EPL
element in the list otherwise.
(It's not clear why you're returning a List<object>
from the data layer to start with. Why not a List<Product>
?)
I think in DAL instead of returning a list of Object
type you should return a list of Product
type. If you do so then there is no need for casting it to Product
type again.
Second thing, in the PL, instead of using IList
just use List
.
精彩评论