具有SQLite引用属性的LinqToDB为null

本文关键字:LinqToDB null 属性 SQLite 引用 具有 | 更新日期: 2023-09-27 18:25:49

我在一个相对简单的域模型上有一些POCO。一个例子如下:

[Table("Tag")]
public partial class Tag
{
    [PrimaryKey, NotNull    ] public string Name        { get; set; } // varchar(128)
    [Column,        Nullable] public string Description { get; set; } // text(2147483647)
    [Column,        Nullable] public string ParentID    { get; set; } // varchar(128)
    #region Associations
    /// <summary>
    /// FK_Tag_0_0
    /// </summary>
    [Association(ThisKey="ParentID", OtherKey="Name", CanBeNull=true)]
    public Tag Parent { get; set; }
    /// <summary>
    /// FK_TagObjects_0_0_BackReference
    /// </summary>
    [Association(ThisKey="Name", OtherKey="TagID", CanBeNull=true)]
    public List<TagObject> ObjectLinks { get; set; }
    /// <summary>
    /// FK_TagSynonyms_0_0_BackReference
    /// </summary>
    [Association(ThisKey="Name", OtherKey="TagID", CanBeNull=true)]
    public List<TagSynonym> SynonymLinks { get; set; }
    /// <summary>
    /// FK_Tag_0_0_BackReference
    /// </summary>
    [Association(ThisKey="Name", OtherKey="ParentID", CanBeNull=true)]
    public List<Tag> Children { get; set; }
    #endregion
}

FK的名称很奇怪,但我通过在.tt文件中为它们指定MemberNames来反驳这一点,就像readme建议的那样。

问题是,当我获取一个标记对象时,所有的关联属性都为null——相关标记的ParentID是正确的,它似乎没有像我预期的那样将其映射到ParentChildren属性。

我做错什么了吗?我已经仔细检查了数据库本身。.tt看起来像这样:

NamespaceName = "MyProg.Models";
GenerateBackReferences   = true;
OneToManyAssociationType = "List<{0}>";
LoadSQLiteMetadata(@"C:'my'path", "my.db");
var k = GetFK("Tag", "FK_Tag_0_0");
k.MemberName = "Parent";
k.BackReference.MemberName = "Children";
GenerateModel();

具有SQLite引用属性的LinqToDB为null

在linq2db中,关联定义表之间的关系。它们有助于使用关联属性导航来构建跨表LINQ查询,而不是像我一样使用LINQ的笨拙的联接语法。

如果您需要在select上用数据填充关联属性,则必须使用LoadWith方法在查询中显式指定它:

var tagsWithChildren = db.Tags.LoadWith(t => t.Children).ToList();

更多的例子可以在这里的测试中找到:https://github.com/linq2db/linq2db/blob/master/Tests/Linq/Linq/LoadWithTests.cs

这就是我克服这个问题的方法-请注意,我使用的是Access数据库。

[Table(Name = "Customers")]
public class Customer
{
    [PrimaryKey, Identity]
    public int CompanyID { get; set; }
    [Column(Name="CompanyName"), NotNull]
    public string Name { get; set; }
    [Association(OtherKey = "CompanyID", ThisKey = "CompanyID", CanBeNull = true)]
    public Account Accounts { get; set; }
}

当关联返回类型为IEnumable时,以下用法返回IQueryable"<"IEnumerable'<'账户>>。

用法:

using (var db = new DbMain())
{
     var q = from c in db.Customers
             select c.Accounts;
     System.Diagnostics.Debug.Print(q.ToList()[0].AccountID);
}