希望這會有所幫助,它是一個稍微修改過的版本。對於SizeCount類 -
using System.ComponentModel.DataAnnotations.Schema;
public class SizeCount
{
public int Id { get; set; }
public int Count { get; set; }
[Index("IX_SizeUnique", 1, IsUnique = true)]
public int SizeId { get; set; }
public virtual Size Size { get; set; }
[Index("IX_ColorUnique", 1, IsUnique = true)]
public int ColorId { get; set; }
public virtual Color Color { get; set; }
[Index("IX_ProductUnique", 1, IsUnique = true)]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
public class Product
{
public int Id { get; set; }
}
public class Color
{
public int Id { get; set; }
}
public class Size
{
public int Id { get; set; }
}
上下文
public class TestDbContext: DbContext
{
public DbSet<SizeCount> SizeCounts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Size> Sizes { get; set; }
public DbSet<Color> Colors { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
我還沒有完全測試的代碼,但也有一些jiggery pokery你應該能夠到那裏。然而,我使用遷移測試了它,生成的表格如下所示:
CreateTable(
"dbo.SizeCounts",
c => new
{
Id = c.Int(nullable: false, identity: true),
Count = c.Int(nullable: false),
SizeId = c.Int(nullable: false),
ColorId = c.Int(nullable: false),
ProductId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Colors", t => t.ColorId, cascadeDelete: true)
.ForeignKey("dbo.Products", t => t.ProductId, cascadeDelete: true)
.ForeignKey("dbo.Sizes", t => t.SizeId, cascadeDelete: true)
.Index(t => t.SizeId, unique: true, name: "IX_SizeUnique")
.Index(t => t.ColorId, unique: true, name: "IX_ColorUnique")
.Index(t => t.ProductId, unique: true, name: "IX_ProductUnique");
因此,簡單地說,您希望'null'被視爲值?也就是說,每列只能使用一次?你爲什麼禁止第三排,但允許第四排? –
是@JᴀʏMᴇᴇ如果可能 – Mashtani
我認爲你正在尋找一個獨特的約束與where子句。這是否可以實現取決於您使用的SQL版本。是2008年,還是更晚? –