3
votes

My question: I would like to add a simple typed property (e.g. string, int, double) to my Entity Framework entity (in my ASP.NET project) that is not associated with any field in the database table that corresponds to the entity. I would like to be able to set the value of this property in my ASP.NET project and have the contents of the property auto-magically sent over to the Silverlight client gets the entities via RIA Services.

How do I do this?

Note: If this makes it easier, for my particular instance, I don't need to save the entities back to the database. Also, it would be great if this worked for views as well as tables.

My setup: I am using Silverlight 4, Entity Framework 4, and RIA Services. It is set up in the normal fashion: Silverlight client application and an ASP.NET server application; I am generating my EF model from the database. RIA services is generating the entities and database access methods on the Silverlight client.

My example:

Database: Customer table

  • CustomerID
  • CustomerName

EF generated entity (ASP.NET server-side): Customer class

  • Public Property CustomerID as Integer
  • Public Property CustomerName as String

I'd like to add a property to the Customer entity that is not associated with the database:

  • Public Property UnicornColor as string

In the my domain service (ASP.NET server side), I'll fill in the new property myself:

Public Function GetCustomers() As IQueryable(Of Customer)
    Dim customers as IQueryable(of Customer) = Me.ObjectContext.Customers
    For each c as Customer in customers
       c.UnicornColor = "Green"
    Next
    return customers
End Function

On the client side, I'd like this new property and its values to be there when I run my query:

Public Sub LoadCustomers()
    myContext.Load(myContext.GetCustomersQuery, AddressOf CustomersLoaded, Nothing)
End Sub

Public Sub CustomersLoaded(ByVal loadOp as LoadOperation(Of Customer))
    Dim customers as IEnumerable(Of Customer) = loadOp.Entities
    For Each c as Customer in customers
        dim color as string = c.UnicornColor
    Next
End Sub
1
I am generating my EF model from an existing database.sparks
To be more clear, I am using the ADO.NET Entity Data Model template and the Entity Data Model Wizard to generate my model and entities, as described here in the "Displaying Data" section: msdn.microsoft.com/en-us/library/ff713719%28v=VS.91%29.aspx I am also creating my domain service as described in the walkthrough.sparks

1 Answers

3
votes

Use T4s to generate partial classes for entities (e.g. the POCOs T4s in the Visual Studio extension gallery) then add a file e.g. MyEntity.Part2.cs with the same partial class as the generated file, but that contains the new properties.

For more info Google partial classes C#.