2017-02-13 79 views
0

什麼是強制子實體獨特的最佳方式?舉例來說,可以說我有一個客戶實體,稱爲營銷活動的強制子實體的唯一性?

public class Customer 
{ 
    public int ID { get; set; } 

    public virtual ICollection<MarketingCampaign> MarketingCampaigns { get; set; } 

} 

public class MarketingCampaign 
{ 
    public int ID { get; set; } 

    public string Name { get; set; } 

} 

子實體集合比方說,如果一個客戶有相同的營銷活動的增加兩倍那麼這將是非常糟糕的,因爲他們會收到重複的材料。

在我的代碼中,我可以在添加它之前檢查它是否存在,但是依賴於每個人都知道它必須是唯一的。

是否有辦法強制這個模型(最好有數據註釋)?

回答

0

您正在尋找一對一或一對一的關係。

您確實可以使用DataAnnotations來完成您正在嘗試執行的操作,但您應該有一個跟蹤客戶/廣告系列關係並將FK返回到Campaign表的中間表。然後用實體框架的魔力,它CustomerMarketingCampaignId將是CustomerMarketingCampaign雙方的PK和FK回Customer

public class Customer 
{ 
    public int CustomerId { get; set; } 

    public virtual ICollection<CustomerMarketingCampaign> CustomerMarketingCampaign { get; set; } 

} 

public class CustomerMarketingCampaign 
{ 
    [ForeignKey("Customer")] 
    public int CustomerMarketingCampaignId 
    [ForeignKey("Campaign")] 
    public int CampaignId { get; set; } 

} 

public class Campaign 
{ 
    public int CampaignId {get;set;} 
    public string Name {get;set;} 
} 
+0

你能告訴我創造的一個例子,分配? – Guerrilla

0

我爲後人最終的解決方案:

public class Customer 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<CustomerMarketingCampaign> CustomerMarketingCampaigns { get; set; } 
} 
public class MarketingAction 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
} 
public class CustomerMarketingCampaign 
{ 
    public int ID { get; set; } 
    [Index("IX_CustomerAndMarketing", 1, IsUnique = true)] 
    public int CustomerID { get; set; } 
    [Index("IX_CustomerAndMarketing", 2, IsUnique = true)] 
    public int MarketingActionID { get; set; } 

    // I also have several properties not included for tracking the progress of the campaign 

    [ForeignKey("CustomerID")] 
    public virtual Customer Customer { get; set; } 
    [ForeignKey("MarketingActionID")] 
    public virtual MarketingAction MarketingAction { get; set; } 
} 
相關問題