2010-10-19 37 views
5

我使用實體框架4創建了一個實體模型,我通過WCF數據服務公開了實體模型。我的一個實體需要定義一些未保存到數據庫的屬性,但實體模型設計器不允許您這樣做。如何使用WCF數據服務公開未保留的屬性?

爲了避開這個我定義我的所有對象爲POCO的對象,它允許您添加的非持續性到您的對象,而不是你的模型。

我的問題是,因爲這些非持續性僅在對象存在本身,而不是模式,他們不通過WCF數據服務暴露出來。

有什麼辦法可以在實體模型中定義未持久化到數據庫的屬性?

預先感謝任何答覆

瑞安

回答

0

好類的模型是局部的。您可以在類的其他部分編寫非持久性屬性。請記下,如果這樣做,因爲我沒有使用WCF數據服務,但每次當我需要一個屬性在業務對象中沒有映射到數據庫中的字段我這樣做。

+0

不幸的是,這已經是我試過的。但是,當您創建對WCF數據服務的服務引用時,這些屬性不會出現在Reference.cs中。 – 2010-10-21 12:34:19

0

我想ikirachen是在正確的軌道上使用部分類來定義其他屬性。爲了讓WCF公開它們,您還必須使用DataMember屬性標記屬性。我創建了一個小WCF服務來測試這一點:

[ServiceContract] 
public interface IService1 
{ 
    [OperationContract] 
    string DoStuff(User user); 
} 

public class Service1 : IService1 
{ 
    public string DoStuff(User user) 
    { 
     string result = string.Empty; 
     foreach (Guid leadId in user.AssociatedLeadIds) 
     { 
      // This is going to console on client, 
      // just making sure we can read the data sent to us 
      result += leadId.ToString() + "\n"; 
     } 

     return result; 
    } 
} 

// partial entity model class 
public partial class User 
{ 
    // This is not persisted to our DB with the user model 
    [DataMember] 
    public ICollection<Guid> AssociatedLeadIds { get; set; } 
} 

這裏是客戶端代碼,展示通過WCF暴露AssociatedLeadIds:

class Program 
{ 
    static void Main(string[] args) 
    { 
     User u = new User 
     { 
      // Here we set our non-persisted property data 
      AssociatedLeadIds = new Guid[] 
      { 
       Guid.NewGuid(), 
       Guid.NewGuid(), 
       Guid.NewGuid() 
      }, 
      // The rest are persisted properties 
      ApplicationId = Guid.NewGuid(), 
      UserName = "TestUser", 
      LoweredUserName = "testuser", 
      LastActivityDate = DateTime.Now, 
      IsAnonymous = false 
     }; 

     using (Service1Client svc = new Service1Client()) 
     { 
      // Here we call the service operation 
      // and print the response to the console 
      Console.WriteLine(svc.DoStuff(u)); 
     } 

     Console.ReadKey(); 
    } 
} 

希望這有助於!

+0

充實代碼多一點。讓我知道你是否仍然無法通過WCF公開屬性。 – jlaneaz 2010-10-25 20:12:59

+0

感謝您的輸入jlaneaz,不幸的是這仍然不適用於我使用WCF數據服務。我想我知道問題是什麼。 Wcf數據服務的服務引用似乎是由EDMX文件而不是代碼庫構建的,因此只有EDMX文件中存在的那些屬性被序列化爲服務引用。 – 2010-10-26 09:49:45

相關問題