I'm trying to make reusable includes and it currently works when I have specific concrete root entity. But let's say I have structure like this:
public class A
{
public B NavigationB { get; set; }
}
public class B
{
public C NavigationC { get; set; }
}
public class C
{
}
And my include extensions
public static class IncludeExtensions
{
public static IQueryable<B> MyIncludesB(this IQueryable<B> query)
{
return query.Include(q => q.NavigationC);
}
public static IQueryable<A> MyIncludesA(this IQueryable<A> query)
{
return query.Include(q => q.NavigationB)
.MyIncludesB(); // how can I implement this
}
}
Basically everything is okay if I have single root e.g. A, but what if I want to do fetch using root B? The idea is to then include everything required for B, but when using A as root then include everything for A, and when including B, reuse MyIncludesB.
I'm not sure if this is possible because include is returning IIncludableQueryable<A, B>, but if anyone has any suggestions, feel free to help!
I think there are numerous possibilities.
My first idea would be to encapsulate the property expression:
public static class IncludeExtensions
{
public static Expression<Func<B, C>> MyIncludeListB()
{
return q => q.NavigationC;
}
public static Expression<Func<A, B>> MyIncludeListA()
{
return q => q.NavigationB;
}
public static IQueryable<B> MyIncludesB(this IQueryable<B> query)
{
return query.Include(MyIncludeListB());
}
public static IQueryable<A> MyIncludesA(this IQueryable<A> query)
{
return query.Include(MyIncludeListA()).ThenInclude(MyIncludeListB());
}
}
As you can see you can pass Expression<Func<B, C>> to the method Include
My second idea is to implement include with strings .Include(string):
public static class IncludeExtensions2
{
public static IEnumerable<string> MyIncludeListB()
{
return "NavigationC".Split(";");
}
public static IEnumerable<string> MyIncludeListA()
{
return "NavigationB;NavigationB.NavigationC".Split(";");
}
public static IQueryable<B> MyIncludesB(this IQueryable<B> query)
{
foreach (var i in MyIncludeListB())
{
query = query.Include(i);
}
return query;
}
public static IQueryable<A> MyIncludesA(this IQueryable<A> query)
{
foreach (var i in MyIncludeListA())
{
query = query.Include(i);
}
return query;
}
}
As you can see you can pass string to the method Include. You can pass the complete chain of navigation properties.
If you want to implement more than one navigation property you have to amend both code examples accordingly.
There are already some questions and answers like yours:
Easy: Entity Framework - Include Multiple Levels of Properties
Hard: Multiple Includes() in EF Core
Related
I looking for some help on how to implement IN clause in the repository pattern. Rather than making single call for each and every record, I will have set of IDs, pass on this IDs to Context to get entities which satisfies the condition using Repository Pattern with EF.
I knew we can have something like this:
context.Students.Where( x => StudentIDs.contains(x.ID))
How to implement same in the repository layer or pattern with single call to DB?
If you really are a purist, yes you should abstract the DbContext entirely as you seem to imply.
I'm not sure I completely understand the issue, but something like that should do the job:
namespace EFRepo
{
class Student
{
public long Id { get; set; }
public string Name { get; set; }
}
class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
class SchoolRepository
{
private SchoolContext context = new SchoolContext();
public Student Add(string name)
{
Student student = new Student { Name = name };
context.Students.Add(student);
context.SaveChanges();
return student;
}
public IEnumerable<Student> GetStudentsByIds(IEnumerable<long> ids)
{
return context.Students.Where(x => ids.Contains(x.Id));
}
}
class Program
{
static void Main(string[] args)
{
SchoolRepository repo = new SchoolRepository();
repo.Add("Bully");
repo.Add("Crawler");
repo.Add("Tart");
foreach (Student s in repo.GetStudentsByIds(new[] { 1L, 3 }))
{
Console.WriteLine(s.Name);
}
}
}
}
Is there a way to inherits from DbSet? I want to add some new properties, like this:
public class PersonSet : DbSet<Person>
{
public int MyProperty { get; set; }
}
But I don't know how to instantiate it in my DbContext
public partial MyContext : DbContext
{
private PersonSet _personSet;
public PersonSet PersonSet
{
get
{
_personSet = Set<Person>(); // Cast Error here
_personSet.MyProperty = 10;
return _personSet;
}
}
}
How can I achieve this?
I have found an answer that works for me. I declare my DbSet properties as my derived interface in my context, e.g.:
IDerivedDbSet<Customer> Customers { get; set; }
IDerivedDbSet<CustomerOrder> CustomerOrders { get; set; }
My implementation includes a private IDbSet which which is assigned in the constructor e.g.:
public class DerivedDbSet<T> : IDerivedDbSet<T> where T : class
{
private readonly IDbSet<T> _dbSet;
public DerivedDbSet(IDbSet<T> dbSet)
{
this._dbSet = dbSet;
}
...
}
My implementation of a derived DbContext interface hides the Set<>() method like so:
new public IDerivedSet<TEntity> Set<TEntity>() where TEntity : class
{
//Instantiate _dbSets if required
if (this._dbSets == null)
{
this._dbSets = new Dictionary<Type, object>();
}
//If already resolved, return stored reference
if (this._dbSets.ContainsKey(typeof (TEntity)))
{
return (IDerivedSet<TEntity>) this._dbSets[typeof (TEntity)];
}
//Otherwise resolve, store reference and return
var resolvedSet = new GlqcSet<TEntity>(base.Set<TEntity>());
this._dbSets.Add(typeof(TEntity), resolvedSet);
return resolvedSet;
}
The derived DbContext returns a newly constructed IDerivedSet or picks it's reference cached in a Dictionary. In the derived DbContext I call a method from the constructor which uses type reflection to go through the DbContexts properties and assigns a value/reference using it's own Set method. See here:
private void AssignDerivedSets()
{
var properties = this.GetType().GetProperties();
var iDerivedSets =
properties.Where(p =>
p.PropertyType.IsInterface &&
p.PropertyType.IsGenericType &&
p.PropertyType.Name.StartsWith("IDerivedSet") &&
p.PropertyType.GetGenericArguments().Count() == 1).ToList();
foreach (var iDerivedSet in iDerivedSets)
{
var entityType = iDerivedSet.PropertyType.GetGenericArguments().FirstOrDefault();
if (entityType != null)
{
var genericSet = this.GetType().GetMethods().FirstOrDefault(m =>
m.IsGenericMethod &&
m.Name.StartsWith("Set") &&
m.GetGenericArguments().Count() == 1);
if (genericSet != null)
{
var setMethod = genericSet.MakeGenericMethod(entityType);
iDerivedSet.SetValue(this, setMethod.Invoke(this, null));
}
}
}
}
Works a treat for me. My context class has navigable set properties of my set type that implements a derived interface inheriting IDbSet. This means I can include query methods on my set type, so that queries are unit testable, instead of using the static extensions from the Queryable class. (The Queryable methods are invoked directly by my own methods).
One solution is to create a class that implements IDbSet and delegates all operations to a real DbSet instance, so you can store state.
public class PersonSet : IDbSet<Person>
{
private readonly DbSet<Person> _dbSet;
public PersonSet(DbSet<Person> dbSet)
{
_dbSet = dbSet;
}
public int MyProperty { get; set; }
#region implementation of IDbSet<Person>
public Person Add(Person entity)
{
return _dbSet.Add(entity);
}
public Person Remove(Person entity)
{
return _dbSet.Remove(entity);
}
/* etc */
#endregion
}
Then in your DbContext, put a getter for your Custom DbSet:
public class MyDbContext: DbContext
{
public DbSet<Person> People { get; set; }
private PersonSet _personSet;
public PersonSet PersonSet
{
get
{
if (_personSet == null)
_personSet = new PersonSet( Set<Person>() );
_personSet.MyProperty = 10;
return _personSet;
}
set
{
_personSet = value;
}
}
}
I solved this using another variable to instantiate the "regular" DbSet.
private DbSet<Person> _persons { get; set; }
public PersonDbSet<Person> Persons { get { return new PersonDbSet(_persons); } }
This way entityframework recognizes the Entity but I can still use my own DbSet class.
I know this is really old and the OP has probably moved on but I was just wondering the same thing myself. EF populates the DbSets inside your MyContext at run time.
I just created MyDbSet<T> that inherits from DbSet<T> and the replaced all references to DbSet<T> with my derived class in MyContext. Running my program failed to instantiate any of the properties.
Next I tried setting the properties to IDbSet<T> since DbSet<T> implements this interface. This DOES work.
Investigating further, the constructors for DbSet are protected and internal (the protected one calls the internal one anyway). So MS have made it pretty hard to roll your own version. You may be able to access the internal constructors through reflection but chances are that EF will not construct your derived class anyway.
I would suggest writing an extension method to plug the functionality into the DbSet object, however you're stuck if you want to store state.
I am trying the EF5 CodeFirst and cannot get the simple setup to work ;(
I have two classes Foo and Bar where Bar represent lookup table.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Bar Bar { get; set; }
}
public class Bar
{
public int Id { get; set; }
public string Description { get; set; }
}
public class MyDbContext : DbContext
{
static MyDbContext()
{
Database.SetInitializer<MyDbContext>(null);
}
public MyDbContext(): base("testEF"){}
public DbSet<Foo> Foos { get; set; }
public DbSet<Bar> Bars { get; set; }
}
Now I have created a static class that serves as DataAccess Layer - in real-world application it will be on different physical tier
public static class DataAccess
{
public static Bar GetBarById(int id)
{
using (var db = new MyDbContext())
{
return db.Bars.SingleOrDefault(b => b.Id == id);
}
}
public static Foo InsertFoo(Foo foo)
{
using (var db = new MyDbContext())
{
db.Foos.Add(foo);
db.SaveChanges();
}
return foo;
}
}
I am initializing the DB with seed method:
internal sealed class Configuration : DbMigrationsConfiguration<testEF.MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(testEF.MyDbContext context)
{
context.Bars.AddOrUpdate(
new Bar { Description = "Bar_1" },
new Bar { Description = "Bar_2" }
);
}
}
This creates two records in Bars table. So far so good...
Here is my Main function
static void Main(string[] args)
{
var bar1 = DataAccess.GetBarById(1);
var foo = new Foo
{
Name = "Foo_1",
Bar = bar1
};
DataAccess.InsertFoo(foo);
}
After the app runes there is a record in the Foos table:
Id Name Bar_Id
1 Foo_1 3
Why Bar_Id is 3? The EF actually inserted new record to Bars table!
Id Description
1 Bar_1
2 Bar_2
3 Bar_1
What I am doing wrong?
UPDATE:
I have found a workaround - to attach Bar property prior to inserting the record:
public static Foo InsertFoo(Foo foo)
{
using (var db = new MyDbContext())
{
db.Bars.Attach(foo.Bar);
db.Foos.Add(foo);
db.SaveChanges();
}
return foo;
}
It is working now but this is more like a hack than a valid solution...
In real-world application the complexity of the objects could become a huge problem.
I am open to better solutions
The problem is that bar1 comes from a different data context. Your InsertFoo method implicitly adds it to the second context by building a relationship with the Foo. You want these two to share a context. So use a single context for the whole scope of the Main method.
The complexity you mention (which I agree with you) is caused by using a static class for your data access component. It forces you to separate your DBContext's across method calls. Instead of doing it that way, why not create a normal class, and build the context in the constructor.
With this, you don't need to attach foo.Bar anymore.
public class DataAccess
{
private MyDbContext _context;
public DataAccess(){
_context = new MyDbContext();
}
public Bar GetBarById(int id)
{
return _context.Bars.SingleOrDefault(b => b.Id == id);
}
public Foo InsertFoo(Foo foo)
{
_context.Foos.Add(foo);
_context.SaveChanges();
return foo;
}
}
There are many ways you can build on and enhance this. You could create an interface for MyDbContext called IDbContext and using a DI framework inject it into this class. Similarly, you could do the same for the DataAccess class and inject that into wherever it's needed.
My domain classes that have one-to-many mappings generally take the following form (untested code):
public Customer Customer
{
// Public methods.
public Order AddOrder(Order order)
{
_orders.Add(order);
}
public Order GetOrder(long id)
{
return _orders.Where(x => x.Id).Single();
}
// etc.
// Private fields.
private ICollection<Order> _orders = new List<Order>();
}
The EF4 code-only samples I've seen expose a public ICollection when dealing with one-to-many relationships.
Is there a way to persist and restore my collections with exposing them? If not, it would appear that my domain objects will be designed to meet the requirements of the ORM, which seems to go against the spirit of the endeavour. Exposing an ICollection (with it's Add, etc. methods) doesn't seem particularly clean, and wouldn't be my default approach.
Update
Found this post that suggests it wasn't possible in May. Of course, the Microsoft poster did say that they were "strongly considering implementing" it (I'd hope so) and we're half a year on, so maybe there's been some progress?
I found that whatever was done, EF requires the ICollection<T> to be public. I think this is because when the objects are loaded from the database, the mapping looks for a collection property, gets the collection and then calls the Add method of the collection to add each of the child objects.
I wanted to ensure that the addition was done through a method on the parent object so created a solution of wrapping the collection, catching the add and directing it to my preferred method of addition.
Extending a List and other collection types was not possible because the Add method is not virtual. One option is to extend Collection class and override the InsertItem method.
I have only focussed on the Add, Remove, and Clear functions of the ICollection<T> interface as those are the ones that can modify the collection.
First, is my base collection wrapper which implements the ICollection<T> interface
The default behaviour is that of a normal collection. However, the caller can specify an alternative Add method to be called. In addition, the caller can enforce that the Add, Remove, Clear operations are not permitted by setting the alternatives to null. This results in NotSupportedException being thrown if anyone tries to use the method.
The throwing of an exception is not as good as preventing access in the first place. However, code should be tested (unit tested) and an exception will be found very quickly and a suitable code change made.
public abstract class WrappedCollectionBase<T> : ICollection<T>
{
private ICollection<T> InnerCollection { get { return GetWrappedCollection(); } }
private Action<T> addItemFunction;
private Func<T, bool> removeItemFunction;
private Action clearFunction;
/// <summary>
/// Default behaviour is to be like a normal collection
/// </summary>
public WrappedCollectionBase()
{
this.addItemFunction = this.AddToInnerCollection;
this.removeItemFunction = this.RemoveFromInnerCollection;
this.clearFunction = this.ClearInnerCollection;
}
public WrappedCollectionBase(Action<T> addItemFunction, Func<T, bool> removeItemFunction, Action clearFunction) : this()
{
this.addItemFunction = addItemFunction;
this.removeItemFunction = removeItemFunction;
this.clearFunction = clearFunction;
}
protected abstract ICollection<T> GetWrappedCollection();
public void Add(T item)
{
if (this.addItemFunction != null)
{
this.addItemFunction(item);
}
else
{
throw new NotSupportedException("Direct addition to this collection is not permitted");
}
}
public void AddToInnerCollection(T item)
{
this.InnerCollection.Add(item);
}
public bool Remove(T item)
{
if (removeItemFunction != null)
{
return removeItemFunction(item);
}
else
{
throw new NotSupportedException("Direct removal from this collection is not permitted");
}
}
public bool RemoveFromInnerCollection(T item)
{
return this.InnerCollection.Remove(item);
}
public void Clear()
{
if (this.clearFunction != null)
{
this.clearFunction();
}
else
{
throw new NotSupportedException("Clearing of this collection is not permitted");
}
}
public void ClearInnerCollection()
{
this.InnerCollection.Clear();
}
public bool Contains(T item)
{
return InnerCollection.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
InnerCollection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return InnerCollection.Count; }
}
public bool IsReadOnly
{
get { return ((ICollection<T>)this.InnerCollection).IsReadOnly; }
}
public IEnumerator<T> GetEnumerator()
{
return InnerCollection.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return InnerCollection.GetEnumerator();
}
}
Given that base class we can use it in two ways. Examples are using the original post objects.
1) Create a specific type of wrapped collection (For example, List)
public class WrappedListCollection : WrappedCollectionBase, IList
{
private List innerList;
public WrappedListCollection(Action<T> addItemFunction, Func<T, bool> removeItemFunction, Action clearFunction)
: base(addItemFunction, removeItemFunction, clearFunction)
{
this.innerList = new List<T>();
}
protected override ICollection<T> GetWrappedCollection()
{
return this.innerList;
}
<...snip....> // fill in implementation of IList if important or don't implement IList
}
This can then be used:
public Customer Customer
{
public ICollection<Order> Orders {get { return _orders; } }
// Public methods.
public void AddOrder(Order order)
{
_orders.AddToInnerCollection(order);
}
// Private fields.
private WrappedListCollection<Order> _orders = new WrappedListCollection<Order>(this.AddOrder, null, null);
}
2) Give a collection to be wrapped using
public class WrappedCollection<T> : WrappedCollectionBase<T>
{
private ICollection<T> wrappedCollection;
public WrappedCollection(ICollection<T> collectionToWrap, Action<T> addItemFunction, Func<T, bool> removeItemFunction, Action clearFunction)
: base(addItemFunction, removeItemFunction, clearFunction)
{
this.wrappedCollection = collectionToWrap;
}
protected override ICollection<T> GetWrappedCollection()
{
return this.wrappedCollection;
}
}
which can be used as follows:
{
public ICollection Orders {get { return _wrappedOrders; } }
// Public methods.
public void AddOrder(Order order)
{
_orders.Add(order);
}
// Private fields.
private ICollection<Order> _orders = new List<Order>();
private WrappedCollection<Order> _wrappedOrders = new WrappedCollection<Order>(_orders, this.AddOrder, null, null);
}
There are some other ways to call the WrappedCollection constructors
For example, to override add but keep remove and clear as normal
private WrappedListCollection<Order> _orders = new WrappedListCollection(this.AddOrder, (Order o) => _orders.RemoveFromInnerCollection(o), () => _orders.ClearInnerCollection());
I agree that it would be best if EF would not require the collection to be public but this solution allows me to control the modification of my collection.
For the problem of preventing access to the collection for querying you can use approach 2) above and set the WrappedCollection GetEnumerator method to throw a NotSupportedException. Then your GetOrder method can stay as it is. A neater method however may be to expose the wrapped collection. For example:
public class WrappedCollection<T> : WrappedCollectionBase<T>
{
public ICollection<T> InnerCollection { get; private set; }
public WrappedCollection(ICollection<T> collectionToWrap, Action<T> addItemFunction, Func<T, bool> removeItemFunction, Action clearFunction)
: base(addItemFunction, removeItemFunction, clearFunction)
{
this.InnerCollection = collectionToWrap;
}
protected override ICollection<T> GetWrappedCollection()
{
return this.InnerCollection;
}
}
Then the call in the GetOrder method would become
_orders.InnerCollection.Where(x => x.Id == id).Single();
Another way to accomplish this would be to create an associated interface for each of your POCOs to expose only what you want outside of the persistence/domain layers. You can also interface your DbContext class to also hide and control access to the DbSet collections. As it turns out, the DbSet properties can be protected, and the model builder will pick them up when it's creating tables, but when you try to access the collections they will be null. A factory method (in my example, CreateNewContext) can be used instead of the constructor to get the interfaced DbContext to conceal the DbSet collections.
There's quite a bit of extra effort in coding, but if hiding implementation details within the POCOs is important, this will work.
UPDATE: It turns out you CAN populate DBSets if they are protected, but not directly in the DBContext. They can't be aggregate roots (i.e. accessibility of the entity has to be through a collection in one of the public DBSet entities). If hiding the implementation of DBSet is important, the interface pattern I've described is still relevant.
public interface ICustomer
{
void AddOrder(IOrder order);
IOrder GetOrder(long id);
}
public Customer : ICustomer
{
// Exposed methods:
void ICustomer.AddOrder(IOrder order)
{
if (order is Order)
orders.Add((Order)order);
else
throw new Exception("Hey! Not a mapped type!");
}
IOrder ICustomer.GetOrder(long id)
{
return orders.Where(x => x.Id).Single();
}
// public collection for EF
// The Order class definition would follow the same interface pattern illustrated
// here for the Customer class.
public ICollection<Order> orders = new List<Order>();
}
public interface IMyContext
{
IEnumerable<ICustomer> GetCustomers();
void AddCustomer(ICustomer customerObject);
ICustomer CreateNewCustomer()
}
public class MyContext : DbContext, IMyContext
{
public static IMyContext CreateNewContext() { return new MyContext(); }
public DbSet<Customer> Customers {get;set;}
public DbSet<Order> Orders {get;set;}
public IEnumerable<ICustomer> GetCustomers()
{
return Customers;
}
public void AddCustomer(ICustomer customerObject)
{
if (customerObject is Customer)
Customers.Add((Customer)customerObject);
else
throw new Exception("Hey! Not a mapped type");
}
public ICustomer CreateNewCustomer()
{
return Customers.Create();
}
// wrap the Removes, Finds, etc as necessary. Remember to add these to the
// DbContext's interface
// Follow this pattern also for Order/IOrder
}
If you change the name of your _orders collection to the name of the orders table in your database, this should work. EF maps table/field names to collections/properties by convention. If you want to use a different name you could edit the mappings in the edmx file.
AFAIK you can just leave the private modifier as it is. Collections do not need to be public.
I've the following simplified code which describes my problem:
public interface IMyUser
{
int Id { get; set; }
string Name { get; set; }
}
Which is used in the dataccess layer like this:
public interface IData
{
T GetUserById<T>(int id) where T : IMyUser, new();
}
The userlogic class is defined as follows:
public class UserLogic
{
private IData da;
public UserLogic(IData da)
{
this.da = da;
}
public IMyUser GetMyUserById(int id)
{
return da.GetUserById<MyUser>(id);
}
}
The userlogic uses a MyUSer class which is only visible internally.
I want to use Moq to mock the call to the dataaccess layer. But becuase I cannot access the MyUser class from my unit test code (which is as designed) , I don't know how to setup moq?
The Moq code should be something like:
var data = new Mock<IData>();
data.Setup(d => d.GetUserById<MyUser ???>(1)).Returns(???);
var logic = new UserLogic(data.Object);
var result = logic.GetMyUserById(1);
How to solve this?
Let me just expand on Sjoerd's answer. The problem you are facing is due to not being able to access MyUser type from the test assembly. That problem is easily fixed with InternalsVisibleTo assembly attribute.
I would however recommend to rethink your design and get rid of IMyUser interface and instead just use MyUser class (which should be public). Normally you put services behind interfaces, not entities. Are there any good reasons for providing multiple implementations of IMyUser?
Have a look at how much cleaner this implementation is:
public interface IData
{
MyUser GetUserById(int id);
}
public class UserLogic
{
private IData da;
public UserLogic(IData da)
{
this.da = da;
}
public MyUser GetMyUserById(int id)
{
return da.GetUserById(id);
}
}
internal class MyUser {
int Id { get; set; }
string Name { get; set; }
}
There is another solution, if you insist on having IMyUser interface and its internal implementation. Your existing solution, if I infer the contents of IData.GetUserById<T> correctly, goes something like this:
public class UserData : IData {
T GetUserById<T>(int id) where T : IMyUser, new(){
T returned = new T();
//fill in properties
returned.Name = "test";
return returned;
}
}
The above code is a slight violation of SRP(warning, PDF) and mixes two responsibilities - retrieving an entity from persistent storage and creating an instance of the entity. Not only that, it also puts the creation responsibility on the interface, which is even worse.
Decoupling those responsibilities using Abstract Factory and Dependency Injection(PDF) patterns will lead to much cleaner design that does not suffer from the same problem as before.
public interface IMyUserFactory {
IMyUser Create();
}
public interface IData
{
IMyUser GetUserById(int id);
}
internal MyUserFactory : IMyUserFactory {
public IMyUser Create() {return new MyUser();}
}
internal class UserData : IData {
IMyUserFactory m_factory;
public UserData(IMyUserFactory factory) {
m_factory = factory;
}
public IMyUser GetUserById(int id) {
IMyUser returned = m_factory.Create();
//fill in properties
returned.Name = "test";
return returned;
}
}
//and finally UserLogic class
public class UserLogic
{
private IData da;
public UserLogic(IData da)
{
this.da = da;
}
public IMyUser GetMyUserById(int id)
{
return da.GetUserById(id);
}
}
//The test then becomes trivial
[TestMethod]
public void Test() {
var data = new Mock<IData>();
data.Setup(d => d.GetUserById(1)).Returns(new Mock<IMyUser>().Object);
var logic = new UserLogic(data.Object);
var result = logic.GetMyUserById(1);
}
Can't you use
da.GetUserById<IMyUser>(id);
instead of
da.GetUserById<MyUser>(id);
If I want to hide functionality but let it be testable, I'll declare the functions as internal, and then at the top of the file I add the [assembly: InternalsVisibleTo("MyAssemblyName")] attribute, where MyAssemblyName is the unit test assembly that you want to grant access to. Thanks, Stef, for pointing out my previous mistake.