【问题标题】:Linq2DB Add Property to ModelLinq2DB 将属性添加到模型
【发布时间】:2019-08-21 17:36:57
【问题描述】:

考虑这样一个简单的模型类和存储库:

public class User
{
    [Column, Nullable] public string Username { get; set; }
    [Column, Nullable] public string Status { get; set; }
    [Column, Nullable] public bool Expired { get; set; }
}

public class UserRepository : IUserRepository
{
    public IQueryable<User> Get(IDataContext context)
    {
        using (context)
        {
            return context.GetTable<User>();
        }
    }
}

我想在读取时向User 类的实例添加一个附加属性,但更新或插入时不需要此属性。所需的模型如下所示:

public class User
{
    [Column, Nullable] public string Username { get; set; }
    [Column, Nullable] public string Status { get; set; }
    [Column, Nullable] public bool Expired { get; set; }

    public string HostName {get; set;}
}

本质上,我想传入一个由调用者提供的主机名值,该值将与对象一起旅行。我可以通过在我的 repo 类中使用 select 语句来做到这一点:

using (context)
{
    return from user in context.GetTable<User>()
           select new User()
           {
               Username = user.Username,
               Status   = user.Status,
               Expired  = user.Expired,
               Hostname = hostName
           }
}

但这感觉不对,我不确定我是否想在我的回购中这样做。此外,我的许多 POCO 类都具有大量属性,这将是令人眼花缭乱的。 Linq2DB 中是否有一种惯用的方式向从数据库检索的对象添加任意属性?谢谢!

【问题讨论】:

    标签: linq2db


    【解决方案1】:

    您可能可以查看OnEntityCreated 事件的上下文。类似的东西:

    context.OnEntityCreated += args =>
    {
        if (arg.Entity is IHostable hostable)
        {
            // I see problem here - where to get hostName itself
            // because context anyway is not multithreaded, it could
            // be a field of current context
            hostable.Hostname = context._hostName;
            // or
            hostable.Hostname = ((IHostProvider)ars.DataContext).HostName;
        }
    };
    

    【讨论】:

    • 我可以假设这是有关如何查找主机名值的指导吗?我想我没有清楚地问这个问题 - 我不是在试图找到主机名,我正在寻找一种更好的实现模式,这种模式对于 Linq 或 Linq2DB 来说是惯用的。也许一个更简单的问这个问题的方法是:“有没有办法在 Linq 查询中设置一个不会影响插入和更新的读取属性?或者是否有一个本地 Linq2DB 功能支持模型上的附加或合成属性对象?”谢谢!
    • 现在我迷路了。我的回答显示了如何使用附加值初始化物化实体。如果您只想从数据库中读取值,但不允许用户插入/更新它 - 使用 SkipOnUpdate \ SkipOnInsert 列属性属性在映射中将您的属性标记为只读
    • 我想我明白你现在所说的,只是无法让它工作!我会坚持下去的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2018-06-26
    相关资源
    最近更新 更多