how to make entity method available at client side? - entity-framework-4

EF + WCF Ria Service:
Suppose I have entity People, because it is a partial class, so I can extend it to add a method to it:
partial class People{
static string GetMyString(){
//......
return string;
}
}
then at client side, I want to method GetMyString available for entity People. what's the best way to implement this?

In your server side project, you should have (but is not necessary) a People.cs class that contains your metadata, such as attributes for validation.
Also in your server project, create a public partial class named People.shared.cs. In this class you can add your methods such as the GetMyString() method. The People.shared.cs class gets code-generated (copied) to the client project.

Related

Annotation for WCF DataContractSerializer to replace ArrayOf with a custom name

I have succesfully implemented a RESTful Web Service using the .NET 4.0 framework with MVC 4 and the ApiController class.
I have a method, let's say GetMovies ("/api/movies") that returns an IQueryable<Movie>. Serialization is done using DataContractSerializer, of course. The problem is in the name of the returned list, because it is ArrayOfMovie:
<ArrayOfMovie>
<Movie></Movie>
<Movie></Movie>
...
<Movie></Movie>
</ArrayOfMovie>
I cannot create a custom class, let's say Movies, and add a [CollectionDataContract(Name = "movies")] annotation (as suggested at https://stackoverflow.com/a/4593167/801065) because I cannot extend IQueryable without implementing all of its methods. And I most definitely need an IQueryable for OData/jQuery processing.
How can I solve this? Is there an annotation that can help me?
This is the solution I found.
You need to put a group class in the main class you want to serialize.
[DataContract(Name = "movies")]
public class group
{
[DataMember(Name="movies")]
public IQueryable<Movie> Movies;
}

Extend EF Entity retrieval methods

I'm using EF 4.2 and originally I had rolled my own repository classes for each entity set. As I investigated further I realised that DbContext and IDbSet implemented the unit of work and repository pattern I required.
This works great, but I would also like some "helper" methods to return particular entities using commonly requested properties, other than the primary key.
For example to select an employee by email and account status rather than the Id primary key. My original user repository had an overload for this.
My question is where should I add this helper method? I see myself as having a few options:
Add a domain logic service type class with this method which uses dbContext, and is consumed by other domain logic classes and methods.
Extend the DbContext class to have an additional method.
Replace the IDbSet with a custom repository.
Wrap the dbContext in additional Repository classes for each entity set, and add a method to the user specific one.
There seem to be pros and cons for each, but I'm leaning more towards 1 or 2. Any thoughts?
You can use custom extension method and reuse it:
public static IQueryable<Employee> Find(this IQueryable<Employee> query,
string email, string status)
{
return query.Where(e => e.Email == email && e.Status == status);
}
Now you will use it simply like:
var employee = context.Employees.Find(email, status).FirstOrDefault();

Validation approach on MVC3 CRUD application with EF4-based WCF as backend

I develop a simple MVC3 CRUD application - simple controllers / views, which uses WCF service for CRUD data access.
The WCF uses EF4.1 with DbContext, and simple CRUD-style methods: ListEntities, GetEntity(ID), AddEntity (entity), DeleteEntity(ID)
If I develop the MVC application directly with EF, code first, I can annotate properties in the entity classes with validation attributes, and the MVC application will automatically recognize validation errors and report them in the UI when I try to save and a validation error occurs (e.g. a required field is not set).
But in my application I don't use this approach and I face two problems:
My entities in the WCF are generated from the EDMX, which in turn was also generated from the database. So I cannot actually add to them any data validation annotation attributes, because they'll vanish as soon as the entities will be regenerated from the EDMX. Is there any solution to this?
Since my client (MVC app) does not share the data contract classes with WCF (for clear separation), but instead it is generated form service reference, even if I find a way to add data annotation attributes to server-side data contract classes, will they be recognized and recreated when the data contract proxy class is created on client side?
So how could I made the MVC application to use client side validation and error message reporting for validation failures when binding to entities exposed by WCF service as data contracts?
One idea I have is, on client side, to create derived classes for all entities exposed as data contracts, and apply annotation attributes to them to desired properties. But this doesn't looks like a good solution to me, because with this I create a logic "coupling" between UI client and the WCF service / data layer (forcing UI to know about data more than it should do - by putting BL logic in client).
Can anyone give me some suggestions on how to handle those this situation?
Thanks
1: Yes you can add validation using the System.ComponentModel.DataAnnotations.MetaDataType.
I answered this question at MVC Partial Model Updates
2a: What you can do is create a seperate Class Library Assembly that contains all the interfaces (with or without additional MetaDataTypes) and use that on both the WCF service and the MVC application. After you add the reference to your MVC application, when adding the WCF Service reference, you can match the WCF Service DataContacts directly to the interfaces in the Assembly. One Caveat is that both the WCF service and MVC application are dependant on the Assembly (some might consider this tightly coupled) but this should be ok because you are only tightly coupling at the interface level, and whether or not you choose to allow VS to recreate it's own interfaces/classes or reuse what you already created in the Assembly it boils down to the same thing in my opinion.
2b: If you decide not to use a Class Library, I'm pretty sure that the service reference classes are partial, and you can simply create another .cs file with partial classes and add the interfaces as I described in part 1 to the partial classes.
Update
I am currently using Entity Framework to access my database. Entity Framework, like WCF References, classes are Auto-Generated classes will look something similar to:
[EdmEntityTypeAttribute(NamespaceName="MyNameSpace", Name="Info ")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Info : EntityObject
{
public static Info CreateInfo (global::System.Int32 id)
{
Info info= new Info ();
info.Id = id;
return info;
}
public string Name { get; set; }
public string FavoriteColor { get; set; }
// etc etc
}
In a separate file with the same namespace as the previous partial class, I have created:
[SomeAttribute1]
[AnotherAttribute2]
public partial class Info: IInfo
{
}
So now my auto-generated class is not only based on an Interface I created IInfo so the actual methods are not exposed (because my datatier in MVC returns interfaces), but it also has Attributes (for Data Annotations or whatever).
What I would suggest is instead of putting your data annotations directly on your WCF Service reference class is to use the MetedataType DataAnnotations. This allows you to separate the actual data object with the data annotations validations. Especially helpful if you want to use the same data class with different validations based on whatever (maybe administrators don't have to have a valid favorite color).
For example:
public interface NormalUser
{
[Required]
string Name { get; set; }
[Required]
string FavoriteColor { get; set; }
}
public interface AdminUser
{
[Required]
string Name { get; set; }
string FavoriteColor { get; set; }
}
[MetadataType(typeof(INormalUser))
public class NormalUserInfo : Info { }
[MetadataType(typeof(IAdminUser))
public class AdminUserInfo : Info { }
In this example we have two different classes NormaUserInfo and AdminUserInfo which both have different validations. Each of them have inherited from Info so they are valid models that can be passed into the WCF Service.
Out of my mind, as I can't test it right now...
Let's say your autogenerated code is like this:
public partial class Employee
{
//some code here
}
You can add a new Employee class, also partial, and this one won't be autogenerated
[you can annotate here]
public partial class Employee
{
//somecode here
}
try it
As for the validation, you could use: http://fluentvalidation.codeplex.com/

Problem with WCF Data service exposing custom partial methods of EF4 model

I am exploring the idea of implementing a web service api using WCF Data Services and EF4. Realizing that some operations require complex business logic, I decided to create a partial class the same name as the main EF data context partial class and implement additional methods there to handle the more complex business logic. When the EF context object is used directly, the additional method shows up (via intellisense) and works properly. When the EF classes are exposed through a WCF Data Service and a Service Reference is created and consumed in another project, the new method does not show up in intellisense or in the generated Service.cs file (of course, I updated the reference and even deleted it and re-added it). The native data methods (i.e. context.AddObject() and context.AddToPeople()) work properly, but the new method isn't even available.
My EF classes look something like this:
namespace PeopleModel
{
//EF generated class
public partial class PeopleEntities : ObjectContext
{
//Constructors here
//Partial Methods here
//etc....
}
//Entity classes here
//My added partial class
public partial class PeopleEntities
{
public void AddPerson(Person person)
{
base.AddObject("People", person);
}
}
}
There's nothing special about the .svc file. The Reference.cs file containing the auto generated proxy classes do not have the new "AddPerson()" method.
My questions are:
1. Any idea why the web service doesn't see the added partial class, but when directly using the EF objects the method is there and works properly?
2. Is using a partial class with additional methods a good solution to the problem of handling complex business rules with an EF generated model?
I like the idea of letting the oData framework provide a querying mechanism on the exposed data objects and the fact that you can have a restful web service with some of the benefits of SOAP.
Service operations are only recognized if they are present on the class which derives from DataService. The WCF Data Service will not look into the context class for these. Also note that methods are not exposed by default, you need to attribute them with either WebGet or WebInvoke and allow access to them in your InitializeService implementation.
http://msdn.microsoft.com/en-us/library/cc668788.aspx

Make a Linq-to-SQL Generated User Class Inherit from MembershipUser

I am currently building a custom Membership Provider for my Asp.net MVC website. I have an existing database with a Users table and I'm using Linq-to-Sql to automatically generates this class for me.
What I would like to do is have this generated User class inherit from the MembershipUser class so I can more easily use it in my custom Membership Provider in methods such as GetUser. I already have all the necessary columns in the table.
Is there any way to do this? Or am I going about this the completely wrong way?
Thanks!
Usually code generation tools creates so called partial classes, like:
public partial class User
{
// class definition here
}
This means that you can extend definition of that class somewhere within the same namespace like that:
public partial class User: MembershipUser
{
// if MembershipUser doesn't have parameterless constructor then you need
// to add here one
}
And then you'll have User class inheriting from MembershipUser.

Resources