Basically I have a Topic Object which can have multiple Category's associted with it. I'm trying to insert a new Category to a particular Topic and I get an error.
Working with ASP.NET 4 , also with windows-1255 encoding on the front-end and in ASP and hebrew_bin on MySQL (the back-end)
ISession session = dal.GetSession();
using (session.BeginTransaction())
{
Topic t = session.Get<Topic>(topicId);
Category c = new Category() { Name=name };
t.AddCategory(c); // updates both references (inside `t` and inside `c`)
session.Update(t);
session.Save(c);
session.Transaction.Commit();
}
Getting Error:
could not insert: [DAL.Models.Category#1][SQL: INSERT INTO Category (Name, Publish, TopicID, ID) VALUES (?, ?, ?, ?)]
Ultimately it fails because of a foreign key constraint violation (I guess ? is not a valid ID):
Cannot add or update a child row: a foreign key constraint fails (
etladaatdb.category, CONSTRAINTFK6482F249B6E2851FOREIGN KEY (ID) REFERENCEStopic(ID))
Topic.cs:
public enum ColorEnum { Blue, Red, Green, Yellow }
public class Topic
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual string ImageUri { get; set; }
public virtual ColorEnum Color { get; set; }
public virtual IList<Category> Categories { get; set; }
public virtual void AddCategory(Category c)
{
Categories.Add(c);
c.Topic = this;
}
}
Topic.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="DAL"
namespace="DAL.Models">
<class name="Topic" lazy="true">
<id name="ID">
<generator class="increment"></generator>
</id>
<property name="Name" />
<property name="Description" />
<property name="ImageUri" />
<property name="Color" type="ColorEnum" />
<bag name="Categories" lazy="true" inverse="true"
batch-size="25" cascade="all-delete-orphan">
<key column="ID" />
<one-to-many class="Category" />
</bag>
</class>
</hibernate-mapping>
Category.cs:
public class Category
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual bool Publish { get; set; }
public virtual Topic Topic { get; set; }
}
Category.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="DAL"
namespace="DAL.Models">
<class name="Category" lazy="true">
<id name="ID">
<generator class="increment"></generator>
</id>
<property name="Name"/>
<property name="Publish" />
<many-to-one name="Topic" class="Topic" column="TopicID" />
</class>
</hibernate-mapping>