0

考虑一个简单的模型类和存储库,如下所示:

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 中是否有一种惯用的方式向从数据库检索的对象添加任意属性?谢谢!

4

1 回答 1

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;
    }
};
于 2019-08-22T07:32:42.267 回答