强制子实体独特的最佳方法是什么?例如,假设我有一个Customer实体和一个名为MarketingCampaign的子实体集合
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; }
}
让我们说如果一个客户添加了两次相同的MarketingCampaign,那么它会非常糟糕,因为他们会收到重复的材料。
在我的代码中,我可以在添加之前检查它是否存在但是依赖于每个人都知道它必须是唯一的。
有没有办法在模型上强制执行此操作(最好使用数据注释)?
答案 0 :(得分:0)
您正在寻找一对一或零关系。
您确实可以使用DataAnnotations来完成您尝试执行的操作,但您应该拥有一个跟踪客户/广告系列关系的中间表,并将FK返回到Campaign表。然后,借助Entity Framework的魔力,它CustomerMarketingCampaign
的PK将成为Customer
的PK,FK又回到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;}
}
/**
* For Exple:
* Spring Controller
* & Tiles View Resolver
* It Works Well
*/
@Controller
public class Home {
@Autowired
private IManager<BaseObject> manager;
public void setManager(IManager<BaseObject> manager) {
this.manager = manager;
}
@RequestMapping(value = "/listprovider", method = RequestMethod.GET)
public String listProvider(ModelMap model) {
model.addAttribute("listprovider",this.manager.getAllProvider());
return "listProviderPage";
// listProviderPage ==> the name of the rendered (Tiles)View.
// it works well
}
}
答案 1 :(得分: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; }
}