我想用标签保存书籍。我的问题是,两本书中的相同标签被保存了两次。
我的课程:
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); }
}
映射是:
<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>
我的代码是:
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);
保存后,我想在表格中有三个标签:编程,计算机和Android。事实上,计算机被保存了两次。原因是因为我使用两个具有相同值的不同引用。
我已经厌倦了在Tag类中覆盖CompareTo,GetHashCode和Equals但没有成功。如果不同引用的值相同,是否有可能阻止将值保存两次?
答案 0 :(得分:2)
您无法使用名称“Computer”创建两次Tag的新实例,并且希望为每个值生成相同的ID。您的代码中没有任何内容告诉nhibernate这两个标签是相同的。
尝试:
var computerTag = new Tag() { Name = "Computer" });
Book book;
book = new Book() { Title = "C#" };
book.Tags.Add(new Tag() { Name = "Programming" });
book.Tags.Add(computerTag);
PersistenceManager.Save(book);
//At this point (due to your mapping, the computerTag has been persisted
//and it will have an ID.
book = new Book() { Title = "Android" };
book.Tags.Add(new Tag() { Name = "OS" });
book.Tags.Add(computerTag);
PersistenceManager.Save(book);