持っているWebフォームアプリを変換して、asp.netMVCを学習しようとしています。これは部屋予約アプリで、tblRentalと1対多の関係を持つ顧客テーブル(tblCustomerBooking)があるため、1人の顧客が複数の部屋を予約できます。互いに一致するフィールドは、tblCustomerBooking.customer_id->tblRental.customer_refです。
最初にコードを使用してモデルクラスを構築しようとしていますが、2つのテーブルをリンクする方法がわからないため、dbContextをクエリすると、1つ以上のレンタルを含む顧客が返されます。同じモデル。
私のテーブル定義は次のとおりです。
CREATE TABLE [dbo].[tblCustomerBooking](
[customer_id] [bigint] IDENTITY(1,1) NOT NULL,
[room_id] [bigint] NULL,
[customer_name] [varchar](110) NULL,
[customer_email] [varchar](50) NULL
CONSTRAINT [PK_tblCustomerBooking] PRIMARY KEY CLUSTERED
(
[customer_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
CREATE TABLE [dbo].[tblRental](
[rental_id] [bigint] IDENTITY(1,1) NOT NULL,
[room_id] [bigint] NOT NULL,
[check_in] [datetime] NOT NULL,
[check_out] [datetime] NOT NULL,
[customer_ref] [bigint] NULL,
[room_cost] [decimal](18, 2) NULL
CONSTRAINT [PK_tblRental_1] PRIMARY KEY CLUSTERED
([rental_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
このためのモデルを構築する私の試みは次のとおりです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity;
namespace MvcApplication23.Models
{
public class tblRental
{
[Key()]
public int rental_id { get; set; }
public int room_id { get; set; }
public DateTime check_in { get; set; }
public DateTime check_out { get; set; }
public long customer_ref { get; set; }
[ForeignKey("customer_ref")]
public tblCustomerBooking Customer {get;set;}
public decimal room_cost { get; set; }
}
public class tblCustomerBooking
{
[Key()]
public long customer_id { get; set; }
public string customer_name { get; set; }
public string customer_email { get; set; }
public ICollection<tblRental> Rentals {get;set;}
}
public class RentalContext : DbContext
{
public DbSet<tblCustomerBooking> customers { get; set; }
public DbSet<tblRental> rentals { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
コントローラ:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using MvcApplication23.Models;
namespace MvcApplication23.api.Controllers
{
public class RentalController : ApiController
{
private RentalContext db = new RentalContext();
// GET /api/rental/5
public IQueryable<tblCustomerBooking> Get(int id)
{
return db.customers.Include("rentals").FirstOrDefault(c=>c.customer_id==id);
}
**データベースにすでに存在する実際のテーブル名を使用して、上記の情報を更新しました**
モデル内の2つのテーブルをリンクするにはどうすればよいですか?そして、customer_idが与えられた場合、tblRentalテーブルに関連するエントリを使用して、DbContextにクエリを実行して顧客を返すにはどうすればよいですか?
ポインタをありがとうございました、
マーク