I have a class with a self-referencing relation. The class is as follows:
public class TableActivity
{
public TableActivity()
{
}
public int TableActivityID {get;set;}
public string Table {get;set;}
public Activity Activity {get;set;}
public virtual ObservableCollection<TableActivity> RelatedActivities {get;set;}
}
in my context class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TableActivity>()
.HasMany<TableActivity>(t => t.TableActivityID)
.WithMany()
.Map(m =>
{
m.ToTable("RelatedActivities");
m.MapLeftKey("TableActivityID");
m.MapRightKey("RelatedTableActivityID");
});
}
I want to add 2 spesific constraints:
- A TableActivity Object can't have itself listed in the RelatedActivities
- For example if we have 2 TableActivity objects o1 and o2 if o1.relatedActivities.contains(o2) then o2.relatedActivities can't have o1 listed
How to achieve this two constraints ?
What I have Done :
I created a helper class that inherits ObservableCollection and I managed the add methode.
public class RelatedTableActivityCollection :ObservableCollection<TableActivity>
{
private TableActivity m_Owner;
public RelatedTableActivityCollection(TableActivity owner)
{
this.m_Owner = owner;
}
public new void Add(TableActivity item)
{
if (m_Owner.Equals(item)) {
return;
} else {
base.Add(item);
}
}
}
The problem with this solution is that it works fine on the application but nothing is done in the database side. Is there a way to make the database take consideration of this changes ?