自联接的模型定义 [英] Model definition for self join
问题描述
我有一个表 - 让我们称之为Doc - 看起来像
I have a table - lets call it Doc - that looks something like
ID int NOT NULL
名称字符串NOT NULL
CurrentVersion int NULL
ID int NOT NULL
Name string NOT NULL
CurrentVersion int NULL
其中,CurrentVersion在Doc上实现自联接,以在表示Doc当前版本及其先前版本的行之间创建关系。
where CurrentVersion effects a self join on Doc to create a relationship between the row which represents the current version of the Doc and its previous versions.
我想创建一个POCO文件,因此
I would like to create a POCO Document thus
public class Document
{
public int Version
{
get;
set;
}
public string Name
{
get;
set;
}
public ICollection PreviousVersions
{
get;
set;
}
}
推荐答案
我取得了一些进展但我迄今为止所解决的解决方案并不完全如我原来的帖子所述。
I have made some progress but the solution I have to date is not quite as set out in my original post.
我想我会发布到目前为止我所拥有的内容,以防它对任何人都有用,并且看看我想要的解决方案是否可以识别。
Thought I would post what I have so far in case it is of use to anyone and to see if the solution I do want can be identified.
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.Infrastructure;
using System.ComponentModel.DataAnnotations;
namespace ERTest
{
public class Document
{
[Key]
public int DocumentID
{
get;
set;
}
public Nullable<int> CurrentVersionID
{
get;
set;
}
public string Name
{
get;
set;
}
public DateTime Created
{
get;
set;
}
[RelatedTo( ForeignKey = "CurrentVersionID" )]
public Document CurrentVersion
{
get;
set;
}
//public ICollection<Document> PreviousVersions
//{
//get;
//set;
//}
}
public class DocumentMapping : EntityConfiguration<Document>
{
public DocumentMapping()
{
MapSingleType
(
d =>
new
{
d.DocumentID,
d.Name,
CurrentVersionID = d.CurrentVersionID,
d.Created
}
)
.ToTable( "Documents" );
HasOptional( c => c.CurrentVersion )
.WithMany()
.HasConstraint( ( a, b ) => a.CurrentVersionID == b.DocumentID );
}
}
public class SelfRefContext : DbContext
{
static SelfRefContext()
{
Database.SetInitializer<SelfRefContext>( null );
}
public SelfRefContext( DbModel model )
: base( model )
{
}
public DbSet<Document> Documents
{
get;
set;
}
}
class Program
{
static void Main( string[] args )
{
ModelBuilder builder = new ModelBuilder();
builder.Configurations.Add( new DocumentMapping() );
var context = new SelfRefContext( builder.CreateModel() );
foreach ( var d in context.Documents.Include( "CurrentVersion" ) )
{
Console.Out.WriteLine( "{0} {1} {2}", d.DocumentID, d.Name, d.Created.ToLongTimeString() );
if ( d.CurrentVersion != null )
{
Console.Out.WriteLine( "Current version has ID {0}", d.CurrentVersionID );
}
}
}
}
}
这篇关于自联接的模型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!