无法通过RIA服务访问EntityObject类型

我的entity framework模型是从SQL Server数据库生成的。 由于我需要从Silverlight访问数据库,因此我针对EF模型为RIAServices生成了一个DomainService。 Product是与表Product对应的自动生成的EntityObject之一。 我试图将自定义类CompositeData传递给Silverlight客户端,如图所示。 问题是客户端无法访问CurrentProduct字段,但可以访问其他字符串/ int字段。 如何使CurrentProduct可以从客户端访问?

 public class CompositeData { [Key] public Guid PKey { get; set; } public string CompositeName { get; set; } public string Identity { get; set; } public Product CurrentProduct { get; set; } //Product is an auto-generated EntityObject class public CompositeData() { PKey = Guid.NewGuid(); } } 

以下是域服务方法:

 [EnableClientAccess()] public class LocalDomainService : DomainService { public IEnumerable GetData() { List listData = new List(); //... return listData; } } 

来自Silverlight客户端,

  domService.Load(domService.GetDataQuery(), GetDataCompleted, null); private void GetDataCompleted(LoadOperation compData) { foreach(CompositeData cdItem in compData.Entities) { // cdItem.CompositeName is accessible // cdItem.CurrentProduct is not accessible! } } 

编辑: Product类在Model1.Designer.cs中自动生成

  [EdmEntityTypeAttribute(NamespaceName="MyDBModel", Name="Product")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Product : EntityObject { //.. } 

它也在客户端项目中生成(在SilverlightProject.g.cs中)

  ///  /// The 'Product' entity class. ///  [DataContract(Namespace="http://schemas.datacontract.org/2004/07/SilverlightProject")] public sealed partial class Product : Entity { //.. } 

您可以使用IncludeAssociation属性定义CompositeDataProduct之间的关系。

 [System.ServiceModel.DomainServices.Server.Include] [System.ComponentModel.DataAnnotations.Association("AssociationName", "MainKey", "AssociatedObjectKey")] public Product CurrentProduct { get; set; } 

(对不起,我的英语不好)

您还需要在DomainService类中公开您的Product实体,以便能够在Silverlight端看到它:

 public IEnumerable GetProduct() { //... return listProduct; } 

这是我快速添加表到我的RIA Silverlight项目的方法。 假设我已经有一个现有的ADO.NET实体数据模型,DomainService.cs和DomainService.metadata.cs

  1. 我更新了我的数据模型
  2. 建立项目
  3. 添加一个全新的域服务类,名称与您拥有的不同。
  4. 在询问时,仅将新表添加到新域服务。 这应该生成一个新的domainservice.cs和一个domainservice.metadata.cs与您的新表的信息。
  5. 从新域服务中复制出自动生成的代码,并将其放在现有域服务中并删除刚刚创建的域服务。
  6. 为元数据做同样的事情。
  7. 建立项目,然后完成。

可以通过CurrentProduct属性定义ExternalReferenceAttribute和AssociationAttribute属性。

 [System.ServiceModel.DomainServices.ExternalReference] [System.ComponentModel.DataAnnotations.Association("AssociationName", "MainKey", "AssociatedObjectKey")] public Product CurrentProduct { get; set; } 

只需将Include属性替换为ExternalReference属性即可。