How do I expose non persisted properties using a WCF Data Service?
I've created an entity model using Entity Framework 4, which I'开发者_运维知识库ve exposed via a WCF Data Service. One of my entities needs to have properties defined that are not persisted to the database, but the Entity Model designer doesn't allow you to do this.
To get round this I've defined all my objects as POCO objects, which allows you to add non persisted properties to your objects, but not your model.
The issue I have is that, because these non persisted properties only exist in the objects themselves and not the model, they are not exposed via the WCF Data Service.
Is there any way to define properties in an entity model that are not persisted to the database?
Thanks in advance for any replies
Ryan
Well the classes for the model are partial. You can write yours non persisted properties in the other parts of the classes. Please write down if this works because I am not using WCF Data Services, but every time when i need a property in business objects which is not mapped to field in the DB I make it that way.
I think ikirachen is on the right track with using a partial class to define additional properties. For WCF to expose them, you must also mark the properties with the DataMember attribute. I created a small WCF service to test this:
[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; }
}
And here is the client code, showing the AssociatedLeadIds exposed via WCF:
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();
}
}
Hopefully this helps!
精彩评论