开发者

Linq2Sql relationships and WCF serialization problem

here is my scenario i got

Table1

  • id
  • name

Table2

  • id
  • family
  • fid

with one to many relationship set between Table1. id and Table2.fid

now here is my WCF service Code

 [OperationContract]

public List<Table1> GetCustomers(string numberToFetch)
{
    using (DataClassesDataContext开发者_StackOverflow社区 context = new DataClassesDataContext())
    {
        return context.Table1s.Take(int.Parse(numberToFetch)).ToList( );
    }
}

and my ASPX page Code

<body xmlns:sys="javascript:Sys"   
    xmlns:dataview="javascript:Sys.UI.DataView">  
  <div id="CustomerView"   
      class="sys-template"  
      sys:attach="dataview"  
      dataview:autofetch="true"  
      dataview:dataprovider="Service2.svc"  
      dataview:fetchParameters="{{ {numberToFetch: 2} }}"  
      dataview:fetchoperation="GetCustomers">  
      <ul>  
          <li>{{family}}</li>  
      </ul>  
  </div> 

though i set serialization mode to Unidirectional in Linq2Sql designer i am not able to get the family value and all what i get is this in firebug

{"d":[{"__type":"Table1:#","id":1,"name":"asd"},{"__type":"Table1:#","id":2,"name":"wewe"}]}

any help would be totally appreciated


Well, the point is: your method GetCustomers only ever selects from Table1 - I don't see any reference at all to Table2, where your Family column is located......

You need to check into Linq-to-SQL JOIN's and how to fetch data from a joined table into your result set.

Something along the lines of:

[DataContract]
class JoinedResult
{   
   [DataMember]
   public int Table1ID { get; set; }
   [DataMember]
   public string Table1Name { get; set; }
   [DataMember]
   public string Table2Family { get; set; }
}  

[OperationContract]
public List<JoinedResult> GetCustomers(int numberToFetch)
{
    using (DataClassesDataContext context = new DataClassesDataContext())
    {
        var q = from t1 in context.Table1
                join t2 in context.Table2 on t1.id = t2.fid
                select new JoinedResult
                           { Table1ID = t1.ID,
                             Table1Name = t1.Name,
                             Table2Family = t2.Family };

        return q.Take(numberToFetch).ToList();
    }
}

and btw: you should really make numberToFetch an INT parameter! Let the caller make the conversion......

UPDATE: if you don't want to explicitly include the second table to be queried, you could instead add a DataLoadOption to your context:

DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Table1>(t => t.Table2);

context.LoadOptions = dlo;

In that case, you tell LINQ to always include all elements from Table2 when it loads anything from Table1 - that should work, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜