0

I've started a sample project with code first and get NULL value from entity which has a foreign key constraint.

my model:

public class CustomerItem
{
     [Key]
     public int Id { get; set; }
     public int Name{get;set;}
     public virtual IEnumerable<OrderItem> Order { get; set; }
}

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

    [ForeignKey("CustomerItem")]
    public int CustomerId { get; set; }
    public virtual CustomerItem CustomerItem { get; set; }
}

dataaccess linq query to get values:

public IEnumerable<CustomerItem> GetOrdersFromCustomerItem(int id)
{
    return (from c in this.dax.Customer
           where c.Id.CompareTo(id) == 0
           select c).AsEnumerable().ToList();
}

this query return NULL orders so I think there's some mistake in this query. How can I wire up this entity with foreign key table?

Thanks

Updated my query to get all customers (and their orders) to this:

public IEnumerable<CustomerItem> GetAllCustomers()
{
    return (from c in this.dax.Customer
            select new 
            {
                //Properties
                OrderItem = c.OrderItem
            }).AsEnumerable.ToList().select(s => new CustomerItem
            {
               //Properties
               OrderItem = s.OrderItem, //here I got the exception I wrote in comment
            }).ToList();
}
nukleos
  • 419
  • 2
  • 8
  • 19

2 Answers2

2

Change:

public virtual IEnumerable<OrderItem> Order { get; set; }

To:

public virtual ICollection<OrderItem> Order { get; set; }

Since IEnumerable<> exposes read-only methods, Entity Framework is basically ignoring it. the property must be of writeable collection type in order to map it to the database.

It is quite common though, to expose an IEnumerable property, and have it's getter returning a backing-field that is really an IList/ICollection.

haim770
  • 48,394
  • 7
  • 105
  • 133
0

You should change the following :

public IEnumerable<CustomerItem> GetOrdersFromCustomerItem(int id)
{
  // You must select CustomerItem not a customer in the previous linq query.
  return (from c in this.dax.Customer
       where c.Id.CompareTo(id) == 0
       select new CustomerItem{

        }).AsEnumerable().ToList();
}
cat916
  • 1,363
  • 10
  • 18
  • 1
    hi minhcat, thanks for your answer but it's still not working after some changes. I've updated my question with my new query and I got this exception "Specified type member not supported in LINQ to Entities". I found some posts about this exception like this: http://stackoverflow.com/questions/9018135/specified-type-member-not-supported-in-linq-to-entities, but I think the types which I'm using should be known by linq-to-entities. – nukleos May 19 '13 at 12:46