我的对象查询返回什么类型?

时间:2010-07-12 11:57:19

标签: asp.net-mvc linq-to-sql types

Public Function List_category() As Myobj 
Dim query = From subcat In _dataContext.subcategories, _ 
cat In _dataContext.categories _ 
Where subcat.CategoryID = cat.CategoryID _
                Select New Myobj() With { _
                .SubcatId = subcat.SubCategoryID, _
                .SubcatName = subcat.SubCategoryName, _
                .CatId = cat.CategoryID, _
                .CatName = cat.CategoryName _
                }
return ?????????
End Function

Public Class Myobj

Private m_SubcatId As Integer
Private m_SubcatName As String
Private m_catId As Integer
Private m_catName As String

Public Property SubcatId() As Integer
    Get
        Return m_SubcatId
    End Get
    Private Set(ByVal value As Integer)
        m_SubcatId = value
    End Set
End Property

Public Property SubcatName() As String
    Get
        Return m_SubcatName
    End Get
    Private Set(ByVal value As String)
        m_SubcatName = value
    End Set
End Property

Public Property CatId() As Integer
    Get
        Return m_catId
    End Get
    Private Set(ByVal value As Integer)
        m_catId = value
    End Set
End Property

Public Property CatName() As String
    Get
        Return m_catName
    End Get
    Private Set(ByVal value As String)
        m_catName = value
    End Set
End Property

结束班

不起作用!!!!

它说无法访问属性'SubcatName'的'Set'访问者。

2 个答案:

答案 0 :(得分:0)

您可以创建自定义类型并修改select以实例化返回。看看这里:Linq To Sql return from function as IQueryable<T>

答案 1 :(得分:0)

编译器只是告诉你,你已经在SubcatName上声明了Private Set,但是ypou正试图在New Myobj()之后为它赋值。

对于第一次运行,您可以声明一个POD类(普通旧数据 - 只是公共数据,没有方法或属性),一旦您看到它运行,您可以调整它,添加方法等。

如果所有属性都是只读的非常重要,那么您需要尝试使查询方法成为同一类的静态成员。

此外,还有一种方法可以返回匿名类型并将其强制转换为在接收方声明的等效匿名类型。接下来要转到C#: - )

示例(read article):

// Method that returns anonymous type as object
object ReturnAnonymous()
{
  return new { City="Prague", Name="Tomas" };
}

// Application entry-point
void Main()
{
  // Get instance of anonymous type with 'City' and 'Name' properties
  object o = ReturnAnonymous();

  // This call to 'Cast' method converts first parameter (object) to the
  // same type as the type of second parameter - which is in this case 
  // anonymous type with 'City' and 'Name' properties
  var typed = Cast(o, new { City="", Name="" });
  Console.WriteLine("Name={0}, City={1}", typed.Name, typed.City);
}

// Cast method - thanks to type inference when calling methods it 
// is possible to cast object to type without knowing the type name
T Cast<T>(object obj, T type)
{
  return (T)obj;
}