Search code examples
c#asp.net-mvcentity-frameworkef-code-firstmodelstate

Using .NET MVC & CodeFirst, is it possible to use a collection of entity ids rather than objects when creating a parent entity?


Let's say I have the following domain model:

  public class ProductApplication
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "Please enter a title.")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Please enter a description.")]
        public string Description { get; set; }

        private ICollection<Product> _products;
        public virtual ICollection<Product> Products
        {
            get { return _products ?? (_products = new Collection<Product>()); }
            set { _products = value; }
        }
    }

In the view, the user creates a new ProductApplication entity complete with a title, description, and a (one-to-many) collection of related products.

Since each product in the collection already exists in the database, I am currently attempting to post the entity to the server using an array of product ids:

{
"Title": "Foo",
"Description": "Bar",
"Products": [1,2,3] //<-- Product Ids
}

Unfortunately, this fails because the server-side controller is expecting an array of product objects; not an array of int.

Short of creating custom business logic, is there a "native" way of accomplishing my desired approach in .NET?


Solution

  • I would create a separate property to get what you want

    [NotMapped]
    public ICollection<int> ProductIds {
       get {
          return Products.Select(p => p.ProductId)
                         .ToList();
    
    }
    

    Or if you really want it to be an array....

    [NotMapped]
    public int[] ProductIds {
        get {
           return Products.Select(p => p.ProductId)
                          .ToArray();
    
        }