簡體   English   中英

如何在兩個相關實體中使用linq?

[英]how to use linq with two related entities?

您好,我在dotnet項目中使用兩個相關實體時遇到問題
我有兩個實體表和保留,我需要獲取為明天保留的表,但是日期是在保留表中設置的,這是代碼

public class Table
{
    public int Id { get; set; }
    public bool isAvailable { get; set; }
    public int Numero { get; set; }
    public virtual ICollection<Reservation> IReservation { get; set; }
}

public class Reservation
{
    public DateTime DateReservation { get; set; }
    public int Id { get; set; }
    public string Nom { get; set; }
    public virtual Table table { get; set; }
}
public class RestaurantContext :DbContext
{
    public DbSet<Table> tTable { set; get; }
    public DbSet<Reservation> tReservation { set; get; }
    public RestaurantContext() : base("RestaurentDB") {     
    }
}
class TableRepository
{
    RestaurantContext rc = null;

    public TableRepository()
    {
        rc = new RestaurantContext();
    }
    public void Commit()
    {
        rc.SaveChanges();
    }
    public void AddTable(Table m)
    {
        rc.tTable.Add(m);
    }

    public IEnumerable<Table> GetAllTables() {
        return rc.tTable.ToList();
    }
    public IEnumerable<Table> GetTablesReserverdTomorrow() {
       ....
    }

在這里,我需要獲取為我嘗試過的明天保留的表

var res=rc.tReservation.Where(r => (r.DateReservation == DateTime.Today.AddDays(1))).ToList();
            var res1 = rc.tTable.Select(r => res.Contains(r.Id));
            return res1;

但似乎有一個錯誤

參數1:無法從int轉換為Reservation

您可以嘗試在查詢中使用導航,例如:

return rc.tReservation
    .Include(reservation => reservation.Table)
    .Where(r => (r.DateReservation == DateTime.Today.AddDays(1)))
    .Select(reservation => reservation.table).ToList();

就您而言,res是IEnumerable,它包含Reservation實例,而不是int值。 根據代碼的邏輯,似乎表和Resrvation應該具有相同的ID才能獲得結果。 我認為您應該將代碼更改為:

var res=rc.tReservation.Where(r => (r.DateReservation == DateTime.Today.AddDays(1))).ToList();
        var res1 = rc.tTable.Where(r => res.Any(resItem=>resItem.Id == r.Id));
        return res1;

我假設您收到的是對實體sql異常的linq。 這意味着您正在嘗試使用SQL Server中不可用的方法。

對於您的問題,我采取了另一種方法:

步驟#1:引入存儲庫方法

/// <summary>
/// A method that allows you to get all tables reserved in a specific period. tables are only returned if they are reserverd.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public IEnumerable<Table> GetAllReservedTables(DateTime start, DateTime end)
{
    return this.rc.tReservation
        // filter by date range
        .Where(x => x.DateReservation >= start && x.DateReservation <= end)

        // ensure table is returned
        .Select(x => x.table);
}

步驟2:調用存儲庫方法並確保您具有正確的日期范圍,即明天:

    TableRepository repo = new TableRepository();

    // figure out the 24 hour period you need to find reserved tables for
    // it is advisible when searching by date to use a date range instead of once specific date
    // the start date and end date will satisfy the 24 hour period of tomorrow.

    // get start tomorrow
    DateTime startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddDays(1);

    // get end of tomorrow
    DateTime endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddDays(2);

    // call the repository method with the date range (the 24 hour period for tomorrow)
    var tablesForTomorrow = repo.GetAllReservedTables(startDate, endDate);

    // dispaly data in console
    foreach(var table in tablesForTomorrow)
    {
        Console.WriteLine("Table Number: #{0}", table.Numero);
    }

請參閱以下完整的解決方案:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReservationTableIssue
{
    class Program
    {
        static void Main(string[] args)
        {

            TableRepository repo = new TableRepository();

            // step #1 - figure out the 24 hour period you need to find reserved tables for
            // it is advisible when searching by date to use a date range instead of once specific date
            // the start date and end date will satisfy the 24 hour period of tomorrow.

            // get start tomorrow
            DateTime startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddDays(1);

            // get end of tomorrow
            DateTime endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddDays(2);

            // call the repository method with the date range (the 24 hour period for tomorrow)
            var tablesForTomorrow = repo.GetAllReservedTables(startDate, endDate);

            // dispaly data in console
            foreach(var table in tablesForTomorrow)
            {
                Console.WriteLine("Table Number: #{0}", table.Numero);
            }

            Console.WriteLine("press any key to exit");
            Console.ReadKey();

        }
    }

    public class Table
    {
        public int Id { get; set; }
        public bool isAvailable { get; set; }
        public int Numero { get; set; }
        public virtual ICollection<Reservation> IReservation { get; set; }
    }

    public class Reservation
    {
        public DateTime DateReservation { get; set; }
        public int Id { get; set; }
        public string Nom { get; set; }
        public virtual Table table { get; set; }
    }
    public class RestaurantContext :DbContext
    {
        public DbSet<Table> tTable { set; get; }
        public DbSet<Reservation> tReservation { set; get; }
        public RestaurantContext() : base("RestaurentDB") {     
        }
    }

    public class TableRepository
    {
        RestaurantContext rc = null;

        public TableRepository()
        {
            rc = new RestaurantContext();
        }
        public void Commit()
        {
            rc.SaveChanges();
        }
        public void AddTable(Table m)
        {
            rc.tTable.Add(m);
        }

        public IEnumerable<Table> GetAllTables()
        {
            return rc.tTable.ToList();
        }

        /// <summary>
        /// A method that allows you to get all tables reserved in a specific period. tables are only returned if they are reserverd.
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public IEnumerable<Table> GetAllReservedTables(DateTime start, DateTime end)
        {
            return this.rc.tReservation
                // filter by date range
                .Where(x => x.DateReservation >= start && x.DateReservation <= end)

                // ensure table is returned
                .Select(x => x.table);
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM