Can WCF First DataServices code return a NotMapped property?

I am using WCF data services for a RESTful API that returns a JSON response.

consider this object:

[Table("person")] public class Person { [Column("dob", TypeName = "datetime")] public DateTime DateOfBirth { get; set; } [NotMapped] public int Age { get { return CalculateAge(); } set { } } } 

WCF does not treat this object as I expected. My service request completely ignores the Age property in serializing the Person object.

I used a workaround where I map the Age property to a dummy database column, and create a setter that does nothing. What an ugly hack! Is there a better way to return a DataService property that does not map to a database column?

+4
source share
4 answers

After much research and lack of evidence to the contrary in stackoverflow, I'm going to go further and say that the answer is: No. WCF DataService with objects mapped using EntityFramework 4 cannot return non-displayable properties.

The ugly hack I used is one that requires you to make a field in a database that is never read.

 [Table("person")] public class Person { [Column("dob", TypeName = "datetime")] public DateTime DateOfBirth { get; set; } [Column("dummy1", TypeName = "int")] public int Age { get { return CalculateAge(); } set { } } } 
+4
source

You may need to use the System.Runtime.Serialization attributes, as WCF would look like.

Not sure if you have logic in your data contracts.

 [Table("person")] [DataContract] public class Person { [Column("dob", TypeName = "datetime")] [DataMember] public DateTime DateOfBirth { get; set; } [NotMapped] [DataMember] public int Age { get { return CalculateAge(); } } } 

EDIT:

You may need a private setter ( How to configure the get-only property for a Silverlight-enabled WCF service )

+2
source

Here is what I used in these situations, similar to what tyrongower indicated:

NOTE: this works with WCF and WCF REST, as well as with JSON

 [DataContract] public class Submission { [NotMapped] [DataMember] public string Location { get { return ""; } set { } } } 
+2
source

I hit this snag too and decided to use extension methods. For instance:

 public static class PersonExtensions { public static int GetAge(this Person person) { // your CalculateAge logic (simplified) return (DateTime.Now - person.DateOfBirth).TotalDays / 365; } } 

Then in your DataServices consumer you can:

 person.GetAge() 

Yes, this is not as good as person.Age , but you also do not add unnecessary database columns.

Update:

Another alternative is to extend the Person class contained in the service reference. You can do this by creating a partial Person class with the same namespace as the Service class Person class. For instance:

 public partial class Person { public string int Age { get { return (DateTime.Now - this.DateOfBirth).TotalDays / 365; } } } 

Then the DataServices Person model will have the Age! Property

0
source

Source: https://habr.com/ru/post/1394513/


All Articles