servicestack ormlite和同一个表的外键

时间:2012-11-17 14:25:25

标签: servicestack ormlite-servicestack

我有一个链接表,一些链接将是子链接,引用父链接ID 但是我无法理解servstack ormlite和填充子项的属性,所有子链接在获取所有链接列表时都会链接。

这是我的模特:

public partial class Navigation
{
   [Alias("Id"), AutoIncrement]
   public int Id  { get; set; }

   [Alias("ParentId")]
   [Display( Name = "ParentId")]
   [References(typeof(Navigation))]
   public int? ParentId  { get; set; }

   [Alias("LinkText")]
   [StringLength(50, ErrorMessage = " Must be no more than 50 characters long!")]
   [Display( Name = "LinkText")]
   public string LinkText  { get; set; }

   [Alias("Action")]
   [StringLength(50, ErrorMessage = " Must be no more than 50 characters long!")]
   [Display( Name = "Action")]
   public string Action  { get; set; }

   [Alias("Controller")]
   [StringLength(50, ErrorMessage = " Must be no more than 50 characters long!")]
   [Display( Name = "Controller")]
   public string Controller  { get; set; }

   [Alias("Area")]
   [StringLength(50, ErrorMessage = " Must be no more than 50 characters long!")]
   [Display( Name = "Area")]
   public string Area  { get; set; }

   [Alias("Visible")]
   [Display( Name = "Visible"),Required(ErrorMessage = " is required" )]
   public bool Visible  { get; set; }

   [Alias("Sequence")]
   [Display( Name = "Sequence")]
   public int? Sequence  { get; set; }

   [ForeignKey(typeof(Navigation))]
   public virtual ICollection<Navigation> Children { get; set; }
}

任何想法?

2 个答案:

答案 0 :(得分:3)

你可以使用继承来做到这一点。父类将包含对子类的引用。我不得不用它来获取哪个用户创建了每个用户。这是一个示例:

public class UserCommon
{
    [References(typeof(User))] // Self reference workaround for User ;)
    public Guid CreatedBy { get; set; }
}

public class User : UserCommon
{
    public Guid Uid { get; set; }
    public String Username { get; set; }
    public String Password { get; set; }
}

您需要注意的是将Id包含在子类中而不是父类中。将生成的表格如下。外键是自引用

Generated Table

获取子项列表应该像简单的LINQ查询一样简单,该查询将获取某个父Guid的所有子项。 CreatedBy也是User继承的属性。

db.Select<User>(q => q.CreatedBy == '734FD814-024D-4795-AFD0-34FECF89A13A');
// Just a sample Guid, you should be able to select
// the Guid you need and insert it here.

答案 1 :(得分:0)

OrmLite中的表格与基础数据库表格严格为 1:1映射

这意味着所有复杂类型属性都是 blobbed 到具有属性名称的db文本字段中,它们从未用于自动映射到子关系,因为您希望在此处执行此操作。

这是一个早期答案,展示了你如何map many to many relations with OrmLite