Reputation: 362
Consider a simple model class and repository like this:
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>();
}
}
}
I'd like to add an additional property to the instances of the User
class on reads, but this property is not needed on updates or inserts. The desired model would look something like this:
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;}
}
Essentially I'd like to pass in a hostname value provided by the caller that will travel with the objects. I can do this by using a select statement in my repo class:
using (context)
{
return from user in context.GetTable<User>()
select new User()
{
Username = user.Username,
Status = user.Status,
Expired = user.Expired,
Hostname = hostName
}
}
But this feels wrong, and I'm not sure I want to do this in my repo anyway. Also, many of my POCO classes have a large number of properties and this will be a eyesore. Is there an idiomatic in Linq2DB way to add an arbitrary property to objects retrieved from the DB? Thanks!
Upvotes: 0
Views: 605
Reputation:
You probably can look at OnEntityCreated
event of context. Something like that:
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;
}
};
Upvotes: 1