0

I have 2 tables that I need to get data from...Rooms and Address. The Rooms table has an AddressID field in it but it can be null, so the relationship is 0 to 1. I've been trying to write a LINQ statement that will return a specific Room AND the Address information if it exists. My model is defined as so:

public partial class Room
{
    public Room()
    {
        this.Address = new HashSet<Address>();
    }

    public int RoomID { get; set; }
    public Nullable<int> AddressID { get; set; }
    public string Comments { get; set; }
    public string Notes { get; set; }

    public virtual ICollection<Address> Address { get; set; }
}

I tried to use the .Include("Address") on the linq statement but it didn't work and I believe it's caused by the Join statement (which I read, once it's used, it silently drops the Include).

Here's an ugly way around it but I know there's a better way:

var csdDB = new CSDContext(CustomerCode);

IList<Room> rooms = (from r in csdDB.Rooms
                        join sr in csdDB.SiteRooms
                            on r.RoomID equals sr.RoomID
                        where sr.SiteID == id
                        orderby r.RoomName
                        select r).ToList<Room>();

int? addressID = rooms.FirstOrDefault<Room>().AddressID;

if (addressID != null)
{
    IList<Address> address = (from a in csdDB.Addresses
                                where a.AddressID == addressID
                                select a).ToList<Address>();

    rooms.FirstOrDefault<Room>().Address = address;
}

I tried to do the filtering directly on the results:

IList<Address> address = (from a in csdDB.Addresses
                            where a.AddressID == rooms.FirstOrDefault().AddressID
                            select a).ToList<Address>();

But it throws an error:

Unable to create a constant value of type 'Models.CSD.Room'. Only primitive types or enumeration types are supported in this context.

Any suggestions on how to make this cleaner/better is appreciated!

4

1 回答 1

0

在 LINQ 中加入左连接可能看起来像这样:

var results = (from r in csdDB.Rooms
               join sr in csdDB.SiteRooms
                   on r.RoomID equals sr.RoomID && sr.SiteID equals id
               join addr in csdDB.Addresses
                   on r.AddressID equals addr.AddressID into roomAddrs
               from roomAddr in roomAddrs.DefaultIfEmpty(new Address())
               select new 
               {
                   Room = r,
                   Address = roomAddr
               }
于 2013-01-17T21:35:33.997 回答