LINQ to SQL mapping associations to create a list of entities
I'm reading Apress Pro ASP.NET MVC Framework and there are some LINQ to SQL examples, but they don't show the database for this example and it's not entirely clear how it works so I was hoping I can get some clarification from the community.
As far as I understand, in the database an Item
cannot have a list of Bid
s, so if we wanted the list we would query the Bids
table for all the Bid
s with a matching ItemID
. In the book's example it looks like there is an association established between the Item
and the Bid
, but I suspect that the Items
table does not have a foreign key which would link it to a Bid
so I have several questions:
- What is the association based on?
- Does LINQ automatically figure out which table to make the association in, based on the associated model (in this case
Bid
is mapped to theBids
table)? - Would the
Bids
property of开发者_Python百科 theItem
model be automatically populated with all the matchingBid
s? If no, then how can it be achieved?
Here is the example
[Table(Name="Members")]
public class Member
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
internal int MemberID { get; set; }
[Column] public string LoginName { get; set; }
[Column] public int ReputationPoints { get; set; }
}
[Table(Name = "Items")]
public class Item
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
public int ItemID { get; internal set; }
[Column] public string Title { get; set; }
[Column] public string Description { get; set; }
[Column] public DateTime AuctionEndDate { get; set; }
[Association(OtherKey = "ItemID")]
private EntitySet<Bid> _bids = new EntitySet<Bid>();
public IList<Bid> Bids { get { return _bids.ToList().AsReadOnly(); } }
}
[Table(Name = "Bids")]
public class Bid
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
internal int BidID { get; set; }
[Column] internal int ItemID { get; set; }
[Column] public DateTime DatePlaced { get; internal set; }
[Column] public decimal BidAmount { get; internal set; }
[Column] internal int MemberID { get; set; }
internal EntityRef<Member> _member;
[Association(ThisKey = "MemberID", Storage = "_member")]
public Member Member {
get { return _member.Entity; }
internal set { _member.Entity = value; MemberID = value.MemberID; }
}
}
Your suspicion for #2 is incorrect; LINQ-to-SQL (like most ORM's) does, in fact, know which table has the actual association. Parent-child relationships can have navigation properties on both sides of the association.
These are taken care of automatically. As for filling the property, that will happen either when loaded explicitly or (if lazy loading is enabled) when you access the property.
精彩评论