在多租户应用程序中,我们可以强制下拉列表中另一个租户的ID,例如
我的模特是:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
此代码应生成类似于此的表:
public class Tenant
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Customer
{
public int Id { get; set; }
public int TenantId { get; set; }
public string Name { get; set;}
}
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public int TenantId { get; set; }
public float Price { get; set; }
}
但是,如何使用 FLUENT API 创建合成?
修改 我想确保传递给Order.cs的CustomerID具有相同的TenantId
也就是说,客户和订单必须具有相同的TenantId
答案 0 :(得分:0)
我想确保传递给Order.cs的CustomerID具有相同的TenantId
在Fludent API中声明复合外键就像声明复合主键一样。使用匿名类型。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.SqlClient;
using System.Linq;
namespace ConsoleApp8
{
public class Tenant
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Customer
{
public int Id { get; set; }
public int TenantId { get; set; }
public virtual Tenant Tenant {get;set;}
public string Name { get; set; }
}
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public int TenantId { get; set; }
public Customer Customer { get; set; }
public Tenant Tenant { get; set; }
public decimal Price { get; set; }
}
class Db : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Tenant>().HasKey(e => e.Id);
modelBuilder.Entity<Customer>().HasKey(e => new { e.TenantId, e.Id });
modelBuilder.Entity<Order>().HasKey(e => new { e.TenantId, e.CustomerId, e.Id });
modelBuilder.Entity<Customer>()
.HasRequired<Tenant>(e => e.Tenant)
.WithMany()
.HasForeignKey(e => e.TenantId);
modelBuilder.Entity<Order>()
.HasRequired<Customer>(e => e.Customer)
.WithMany()
.HasForeignKey(e => new { e.TenantId, e.CustomerId });
modelBuilder.Entity<Order>()
.HasRequired<Tenant>(e => e.Tenant)
.WithMany()
.HasForeignKey(e => e.TenantId)
.WillCascadeOnDelete(false);
}
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseAlways<Db>());
using (var db = new Db())
{
db.Database.Log = m => Console.WriteLine(m);
db.Database.Initialize(true);
}
Console.WriteLine("Hit any key to exit");
Console.ReadKey();
}
}
}