Adding custom property to object returned from WCF RIA Services - wcf-ria-services

I have a stored procedure in my Entity Framework Model. I've added a Function Import and mapped the results to a Complex Type.
I want to add an extra property to this Complex type, that I'll populate in my Domain Service, not coming back from the stored procedure. I added a myClass.shared.cs file and implemented added the property like so:
//myClass.shared.cs
public partial class myClass
{
public string myProperty {get;set;}
}
I populate this in my domain service when I return the object, e.g.:
public myClass GetMyClass(int myClassID)
{
myClass theClass= this.ObjectContext.StoredProc(myClassID).FirstOrDefault();
class.myProperty = 12345;
return theClass;
}
When I get the return values of this method on the client side theClass.myProperty is always null but all values from the stored procedure are populated, am I missing something?
I've tried decorating the myProperty with the [DataMember] attribute but this throws the error:
"The type 'myClass' already contains a
definition for 'myProperty'"
How can I get this to return the value set in the Domain Service to the client?

There was no need to put this in the shared.cs class. The shared.cs class copies the actual code over to the client side and is useful for adding methods etc. but to add a new property, all I had to do was add a partial class (NOT in myClass.shared.cs) and decorate it with DataMember.
public partial class myClass
{
[DataMember]
public string myProperty {get;set;}
}

Related

Can non-integer enums be used in Entity Framework?

I'm using Entity Framework 6.1 (.NET 4.5) and noticed something strange:
A simple enum property in an entity class works fine when defined like this:
public enum TestEnum
{
ValueOne,
ValueTwo
}
//then used in an entity class like this:
public class MyClass
{
public TestEnum MyTestEnum { get; set; }
}
... but not when it's defined as a non-int32 type, like this:
public enum TestEnum : ushort
...
With the former, Entity Framework detects and maps the property automatically to an int column. With the latter, EF doesn't even detect that the property exists in the entity class. If I try to force it,
...Property(x => x.MyTestEnum).IsRequired();
I get the following migration error:
The property 'MyTestEnum' is not a declared property on type 'MyClass'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property.
So are ushort enums not supported in EF?

Entity Framework Object not allowing Connection String to be passed as parameter

I am trying to initialize an Entity object (ADO.NET EF Object), but it does not allow me to choose what connection string I want to use. I need to change connection string in order to give different access levels to users.
There are no overrides in the Entities Object, just a parameterless constructor.
If anyone can give me any pointers, it is appreciated.
If you have used the designer to generate an .edmx file for you, you will have something like below:
public MyEntities() : base("name=MyEntities", "MyEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
This will by default, get the connection string from your configuration file.
What you could do in this case is set the connection string
public partial class MyEntities
{
partial void OnContextCreated()
{
//Dynamically Building a Connection String
this.Connection.ConnectionString = "myconnectionstring";
}
}
Bear in mind though that this will first use the base constructor to pull the connection string from config, then set it with your custom version, basically overriding the connection string. This is typically good when you always want a default connection string.
Another option if you want a bit more control, is pass the connection string in via the constructor as shown below:
public partial class MyEntities
{
public MyEntities(string connectionString) :
base(connectionString,"MyEntities")
{
this.OnContextCreated();
}
}
Now you are passing in the connection string down to the base class and this is the only one it will use. This does mean however that you will most often need to supply this each time.
Hope this helps...

Serialization in ASP.NET Web API

I am using XmlSerializer instead of DataContractSerializer in my ASP.NET Web API project and have a return object defined as
Response Object
public class MyResponse
{
public string Name {get;set;}
public CustomField<string> Username {get;set;}
public CustomField<float?> Score {get;set;}
}
Custom Field
public class CustomField<T>
{
public T Value {get;set;}
public long LastModified {get;set;}
}
I want to generate an XML response as
<MyResponse>
<FirstName>ABC</FirstName>
<Username lastModified="1234">XYZ</Username>
<Score lastModified="45678">12002</Score>
</MyResponse>
ASP.NET Web API returns a JSON object (I am aware that this happens when XmlSerialization does not work correctly) when I decorate the CustomField class as
public class CustomField<T>
{
[XmlText]
public T Value {get;set;}
[XmlAttribute]
public long LastModified {get;set;}
}
How can I get the desired XML response ?
Alright, I think I know what's going on.
If you try to run
new XmlSerializer(typeof(MyResponse))
you'll get this error:
System.InvalidOperationException: Cannot serialize member 'Value' of type System.Nullable`1[System.Single]. XmlAttribute/XmlText cannot be used to encode complex types.
So the issue is that you have a field of type 'float?' as an [XmlText]. [XmlText] can only be applied to primitives, and it doesn't look like XmlSerializer recognizes 'float?' as a primitive. If you use 'float' instead of 'float?', everything looks to be working right. If you want to indicate that sometimes there is no Score, you may want to set the Score to null instead of the Score's value to null.
Hope that helps.

How to solve field wrapping in Entity Framework database-first

When I use database first, after creating the edmx file, all the conceptual models have already been generated. But I want to do some special operations on certain fields. For example, there's a field named 'price'; I want the matching property 'Price' to return double of the 'price'. How can I do that? If I modify the getter in the code, every time I update the model from database, all of the modifications go away.
What's the correct way to do this?
What you can do is create a partial class for entity which contains the Price Property and put a getter like this (A property with double price will be meaningful ),
Public partial class YourEntity{
Public float DoublePrice{
get { return Price*2;}
}
}
Or you can create a class inherited from the entity,
Public partial class Entity:YourEntity{
Public override float Price{
get { return base.Price*2;}
}
}

Entity Framework and implementation of IPrincipal/IIdentity

As far as I am aware, for the property to be saved in the database it cannot be ReadOnly.
IIdentity properties: AuthenticationType, IsAuthenticated and Name are all ReadOnly.
Is making the wrapper to the properties that need to be saved the only solution or there are better ones?
EDIT:
I might not have explained my question that well. Here is the sample code for one of the ReadOnly properties, I have added UserName property for the Entity Framework:
Public Property UserName As String
Get
Return _userName
End Get
Private Set(value As String)
userName = value
End Set
Public ReadOnly Property Name As String Implements System.Security.Principal.IIdentity.Name
Get
Return UserName
End Get
End Property
What I wanted to ask is if there is any better way of doing it.
IIdentity properties are read only but the implementation can have setters. If you are using EDMX for mapping you don't have to expose these setters as public.
Edit:
This is possible in C# so hopefully you can use similar approach with VB.NET (I can only read VB code, not write):
public interface ITest {
string Name { get; }
}
public class Test : ITest {
public string Name { get; set; }
}
The class offers setter even the interface didn't define it.
The EF persists objects, not interfaces. Your object can have whatever properties you would like it to have. You cannot add an interface to your entity model, but you can add an object type which implements that interface.