I have a child , parent relationship in my application e.g.One Post can have many Comments(One to Many relationship). Ive completed the code for mapping, I need to write a code so when I insert a child into DB it inserts the parent ID too. At the moment my code doesnt insert the parent id only inserts other details of child.Can someone help me unpdating my code please?
Models:
namespace MvcApplication7.Models
{
public class Post
{
public virtual int Id { get; set; }
[Display(Name = "Post")]
public virtual string PostText { get; set; }
public virtual IList<Comment> Comments { get; set; }
}
}
namespace MvcApplication7.Models
{
public class Comment
{
public virtual int Id { get; set; }
public virtual Post Post { get; set; }
[Display(Name = "Comments")]
public virtual string CommentText { get; set; }
}
}
NHibenate mappings:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="MvcApplication7" namespace="MvcApplication7.Models">
<class name="Post" table="Posts" dynamic-update="true" >
<cache usage="read-write"/>
<id name="Id" column="Id" type="int">
<generator class="sequence">
<param name="sequence">posts_id_seq</param>
</generator>
</id>
<property name="PostText" column="Post"/>
<bag name="Comments" inverse="true" lazy="true" >
<key column="PostId"/>
<one-to-many class="Comment"/>
</bag>
</class>
<class name="Comment" table="Comments" dynamic-update="true" >
<cache usage="read-write"/>
<id name="Id" column="CommentId" type="int">
<generator class="sequence">
<param name="sequence">comments_commentid_seq</param>
</generator>
</id>
<property name="CommentText" column="Comment"/>
<many-to-one name="Post" class="Post" column="PostId" />
</class>
</hibernate-mapping>
Database tables:
CREATE TABLE comments
(
commentid serial NOT NULL,
postid integer,
comment text,
CONSTRAINT commentid PRIMARY KEY (commentid),
CONSTRAINT postid FOREIGN KEY (postid)
REFERENCES posts (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE comments
OWNER TO postgres;
*********************************************************
CREATE TABLE posts
(
id serial NOT NULL,
post text,
CONSTRAINT id PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE posts
OWNER TO postgres;
The code that needs updating is the MVC controller which is as follows:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Comment comments)
{
try
{
using (ISession session = NHIbernateSession.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(comments);
transaction.Commit();
}
}
return RedirectToAction("Index");
}
catch (Exception exception)
{
return View();
}
}
Postproperty of theCommentto thePostand adding theCommentto thePost'sCommentcollection? That's all that you should have to do.