سؤال

I have a IQueryable method as below:

public IQueryable<vmTest> TestMethod(long ID)
{
    return from m in db.table1
           join n in db.table2
           on m.table1_ID equals n.table1_ID into tabC
           from c in tabC
           join o in db.table3
           on m.table3_ID equals o.table3_ID
           where m.table1_ID.Equals(ID)
           select new vmTest{ field1 = m.xxx };
}

from the code above, m.xxx is a long type and in the vmTest there is a public long field1. There is error with m.xxx which saying Cannot implicitly convert type 'long?' to 'long'.An explicit conversion exists (are you missing a cast?).May I know what's wrong?

Additional information:
If i cast (long) in front of m.xxx, error will be dissapear but another problem occur when this query returning no value as it's wrong to cast long to null

هل كانت مفيدة؟

المحلول

You have several solutions:

  • You can change vmTest class definition and replace field1 type from long to long?
  • You can change your table in database and transforms xxx from NULL to NOT NULL then xxx will become a long
  • You can use a condition in your query like

    new vmTest { field1 = m.xxx.HasValue ? m.xxx.Value : 0 }
    

More information on Nullables here

نصائح أخرى

if you are sure of the types you want to use, you could try this:

public IQueryable<vmTest> TestMethod(long ID)
{
    return from m in db.table1
           join n in db.table2
           on m.table1_ID equals n.table1_ID into tabC
           from c in tabC
           join o in db.table3
           on m.table3_ID equals o.table3_ID
           where m.table1_ID.Equals(ID)
           select new vmTest
               { 
                    field1 = m.xxx.HasValue 
                        ? m.xxx.Value
                        : default(long) /*or something else, or an exception maybe... according to your expectation in this case*/ };
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top