Note that there are some explanatory texts on larger screens.

plurals
  1. PONon-keyed associations with Entity Framework
    primarykey
    data
    text
    <p>I am having problems setting up an association in entity framework between two tables where the association does not contain all the primary key values.</p> <p>e.g. I have two tables (this is a contrived example, but it is sufficient to represent my real database which I cannot change)</p> <pre><code>------Items------ ---Orders---- ----------------- ------------- * ItemId - * OrderId - * EffectiveDate - - OrderDate - - Name - - ItemId - ----------------- ------------- * denotes primary key field </code></pre> <p>Ideally I'd like a property on Orders that indicates the Item that was effective at OrderDate, but I could live with an association on Order to a collection of Items and then create a readonly property on Order that selected the correct Item.</p> <p>EDIT: The database and model will be read-only so read-only solutions are OK.</p> <p>Is this possible in entity framework? (or even LINQ to SQL?)</p> <p>I believe that it is possible using NHibernate (can anyone confirm?) but I keep hitting brick walls with entity framework. So far the only solution I have managed is to create a property in the partial class for Order that uses a '<a href="http://blogs.msdn.com/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity.aspx" rel="nofollow">hack</a>' to access the ObjectContext from order and query the context.Items collection directly as such</p> <pre><code>private IEnumerable&lt;Item&gt; Items { get { var ctx = this.GetContext(); return from i in ctx.Items where i.ItemId == this.ItemId select i; } } public Item Item { get { return (from i in Items where i.EffectiveDate &lt;= this.OrderDate orderby i.EffectiveDate ascending select i).First(); } } </code></pre> <p>Is there a better solution?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload