Question

So I am building a REST service using EF and WebAPI. I have a two classes like this

public class App 
{
  [Key]
  public int ID {get;set;}

  public virtual ICollection<User> Users {get;set;}
}

 public class User
{
  [Key]
  public int ID {get;set;}

  public virtual ICollection<App> Apps {get;set;}
}

I can see that EF correctly creates the tables and everything is peachy. The problem, is I can't post composed objects through REST, I need to post by ID references and compose them on the server level.

 public class UserViewModel
{
  [Key]
  public int ID {get;set;}

  public virtual ICollection<Int> Apps {get;set;}
}


//Automapper config
Mapper.CreateMap<User, UserViewModel>();

I tried doing this with the Automapper, however it is not doing the Object -> ID map on its own. Is there a way to accomplish this without using automapper, or if not, how to do this with automapper?

A good example of the behavior I am expecting is found here-

 public class Enrollment
{
    public int EnrollmentID { get; set; }
    public int CourseID { get; set; }
    public int StudentID { get; set; }
    public Grade? Grade { get; set; }

    public virtual Course Course { get; set; }
    public virtual Student Student { get; set; }
}

You can see that Enrollment has a property called CourseID. According to the article "The CourseID property is a foreign key, and the corresponding navigation property is Course." So this maps quite well to a WebAPI REST service, you ignore the Course property and map the CourseID to a viewmodel and POST the enrollment object with the CourseID string. However, how can I translate this behavior to a collection of courses or a many to many relationship?

Was it helpful?

Solution 2

I was able to resolve this with the following for mapping Model -> DTO (using automapper)

        Mapper.CreateMap<User, UserViewModel>()
            .ForMember(u => u.App, opt => opt.ResolveUsing(u => u.Apps.Select(app=> app.ID)));

And manually mapping the IDs to objects in the controller on the way in from the client.

OTHER TIPS

Have you tried handling this kind of object creation through a service like Angular?

If you're looking to use some form crud functionality with some angular and web api, this tutorial is a good place to start: http://code.msdn.microsoft.com/CRUD-Grid-Using-AngularJS-84afaf13

Also, don't use EF. Use Dapper .NET! https://code.google.com/p/dapper-dot-net/

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top