我要通过创建三个领域模型来描绘这一问题:一个点物体,一个线标,包含两个点物体,一个名为“StartPoint”和一个名为“EndPoint”的物体,另一个是含有一线数字的多角物体。 域名希望:
public class Point
{
public int Id { get; set; }
public int XVal {get; set;}
public int YVal {get; set;}
}
public class Line
{
public int Id {get; set;}
public Point StartPoint {get; set;}
public Point EndPoint {get; set;}
}
public class Polygon
{
public Polygon()
{
Lines = new HashSet<Line>();
}
public int Id {get; set;}
public string Description { get; set; }
public ICollection<Line> Lines { get; set; }
}
You could persist this class using a database schema that has a table for each domain model object.
The DDL to establish this database structure:
create table Point
(
PointId int primary key identity(1, 1),
XVal int,
YVal int
)
create table Polygon
(
PolygonId int primary key identity(1, 1),
[Description] nvarchar(255)
)
create table Line
(
LineId int primary key identity(1, 1),
PolygonId int foreign key references Polygon(PolygonId),
StartPointId int foreign key references Point(PointId),
EndPointId int foreign key references Point(PointId)
)
您的最后任务是撰写你的最佳制图文件,将域模型绘制到基础数据库表。 如下所示。 请注意,我将“学校”的属性定为“所有”,以满足你的要求,即拯救母体圆形物体,改变儿童物体。
<class name="Polygon" table="Polygon" lazy="false" >
<id name="Id" column="PolygonId">
<generator class="identity" />
</id>
<property name="Description" column="Description" />
<set name="Lines" table="Line" lazy="false" cascade="all">
<key column="PolygonId" />
<one-to-many class="Line" />
</set>
</class>
<class name="Line" table="Line" lazy="false">
<id name="Id" column="LineId">
<generator class="identity" />
</id>
<many-to-one name="StartPoint" column="StartPointId" class="Point" cascade="all"/>
<many-to-one name="EndPoint" column="EndPointId" class="Point" cascade="all"/>
</class>
</hibernate-mapping>
有了这种绘图,你就可以操纵你的母子多功能物体,在保存数据库时,整个物体图将一直保留到数据库。 例如,为了在多角物体上添加一条新线,你可以使用以下代码:
using (var session = factory.OpenSession())
using(var tran = session.BeginTransaction())
{
var newPoint = session.Get<Point>(5);
var newPoint2 = session.Get<Point>(2);
var newLine = new Line { StartPoint = newPoint, EndPoint = newPoint2 };
var foo2 = session.Get<Polygon>(1);
foo2.Lines.Add(newLine);
session.SaveOrUpdate(foo2);
tran.Commit();
}
Edit:
The above mapping assumes that you always want to access Line objects only thru the parent Polygon object. If you want to access Lines directly, you may want to add a many-to-one reference from the Line object to the Polygon parent. To do this, you will need to add the following property to the Line class:
public Polygon Polygon {get; set;}
此外,在线路制图档案中添加相应的绘图:
<many-to-one class="Polygon" name="Polygon" lazy="false" />
With these changes, you should now be able to directly load a Line object that contains it s Polygon parent:
var line = session.Get<Line>(5);
var parent = line.Polygon;
Edit 2
Note that if you make the Polygon-Line association bidirectional, you will need to add code to your domain model to ensure graph consistency. See for example this SO post.