2016-01-04 45 views
0

我使用實體框架版本6,我有這樣一個模型:如何使用實體框架爲可空列設置唯一約束?

public class SizeCount 
    { 
     public int Count { get; set; } 
     public Size Size { get; set; } 
     public long? SizeId { get; set; } 
     public Color Color { get; set; } 
     public long? ColorId { get; set; } 
     public Product Product { get; set; } 
     public long ProductId { get; set; } 
    } 

我想從ColorIdSizeId防止雙方爲空,我想ProductIdColorIdSizeId是唯一的。 一些示例記錄:

ProductId SizeId ColorId 
1   null 1  > allow 
1   null 1  > not allow 
1   1  null > not allow 
2   1  null > allow 
2   null 1  > not allow 

SizeIdColorId可以爲空。 是否有任何屬性可以幫助我在實體框架中,或者我應該手動檢查它?

+0

因此,簡單地說,您希望'null'被視爲值?也就是說,每列只能使用一次?你爲什麼禁止第三排,但允許第四排? –

+0

是@JᴀʏMᴇᴇ如果可能 – Mashtani

+0

我認爲你正在尋找一個獨特的約束與where子句。這是否可以實現取決於您使用的SQL版本。是2008年,還是更晚? –

回答

0

希望這會有所幫助,它是一個稍微修改過的版本。對於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");