I'd like to save books with tags. My problem is, the same tag in two books is saved twice.
My classes:
public class Book
{
public virtual long ID { get; set; }
public virtual string Title { get; set; }
protected ICollection<Tag> _Tags = new List<Tag>();
public virtual ICollection<Tag> Tags { get { return _Tags; } set { _Tags = value; } }
}
public class Tag: IComparable
{
public virtual long ID { get; set; }
public virtual string Name { get; set; }
public override string ToString() { return Name; }
public virtual int CompareTo(object obj) { return string.Compare(Name, ((Tag)obj).Name); }
public override int GetHashCode() { return Name.GetHashCode(); }
public override bool Equals(object obj) { return Name.Equals(((Tag)obj).Name); }
}
The mapping is:
<class name="Book" table="Books">
<id name="ID">
<generator class="identity"/>
</id>
<property name="Title"/>
<set name="Tags" table="BookTags" cascade="all-delete-orphan">
<key column ="BookID" />
<many-to-many class="Tag" column="TagID" />
</set>
</class>
<class name="Tag" table="Tags">
<id name="ID">
<generator class="identity"/>
</id>
<property name="Name"/>
</class>
My code is:
Book book;
book = new Book() { Title = "C#" };
book.Tags.Add(new Tag() { Name = "Programming" });
book.Tags.Add(new Tag() { Name = "Computer" });
PersistenceManager.Save(book);
book = new Book() { Title = "Android" };
book.Tags.Add(new Tag() { Name = "OS" });
book.Tags.Add(new Tag() { Name = "Computer" });
PersistenceManager.Save(book);
After saving, I'd like to have three Tags in the table Tags: Programming, Computer and Android. In fact, Computer is saved twice. The reason is because I use two different references with the same value.
I've tired to override CompareTo, GetHashCode and Equals in the Tag class with no success. Is there any possibility to prevent saving the value twice if the values of different references are the same?