在Entity Framework Code First模型中链接两个表

时间:2012-06-04 09:20:34

标签: entity-framework code-first entity-relationship

我正在尝试通过转换我拥有的网络表单应用程序来学习asp.net MVC。这是一个房间预订应用程序,其中有一个客户表(tblCustomerBooking)与tblRental有一对多的关系 - 所以一个客户可以预订多个房间。彼此匹配的字段是tblCustomerBooking.customer_id - > tblRental.customer_ref

我正在尝试首先使用代码 - 并构建一个模型类 - 但我无法弄清楚如何链接这两个表,这样当我查询dbContext时,它将返回一个客户,有一个或多个在同一型号内租赁。

我的表定义是:

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);
        }

**我已经使用数据库中已存在的实际表名更新了上面的信息**

如何链接模型中的两个表?然后给出一个customer_id,我如何查询DbContext以返回一个客户,以及tblRental表中的任何相关条目?

非常感谢您的任何指示,

标记

2 个答案:

答案 0 :(得分:5)

要链接两个实体,请提供导航属性:

public class Rental
{
    [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 int customer_ref { get; set; }

    [ForeignKey("customer_ref")]
    public virtual Customer Customer {get;set;}

    public decimal room_cost { get; set; }
 }

public class Customer
{
    [Key]
    public int customer_id { get; set; }
    public string customer_name { get; set; }
    public string customer_email { get; set; }

    public virtual ICollection<Rental> Rentals {get;set;}
}

并询问您的客户:

return this.DataContext.customers.Include("Rentals").FirstOrDefaul(c=>c.customer_id==customerId);

答案 1 :(得分:0)

using System.ComponentModel.DataAnnotations.Schema;


public class Rental
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int id { get; set; }
    public virtual int room_id { get; set; }
    public virtual DateTime check_in { get; set; }
    public virtual DateTime check_out { get; set; }
    public virtual int customer_id { get; set; }
    public virtual decimal room_cost { get; set; }

    #region Navigation Properties
    [ForeignKey("customer_id")]
    public virtual Customer Customer {  get;  set;  }
    #endregion
}

public class Customer
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }
    public string name { get; set; }
    public string email { get; set; }

    public virtual ICollection<Rental> Rentals {get;set;}
}