I am creating a general repository class as part of my Entity Framework Code First data layer. To get the single row by id, if all the entities have id name as "ID" it will work as shown by the following:
public T GetSingle(int id)
{
return GetAll().FirstOrDefault(x => x.ID == id);
}
But I would like to name my entity primarykey as "EnityName"+Id, such as AddressId or ApplicantId etc. Is there any way to have the code:
return GetAll().FirstOrDefault(x => x.<EntityName>Id == id);
to make to work?
Thanks
You can do it easier only create method "Get single" and pass predicate
public virtual T GetSingle(Expression<Func<T, bool>> predicate)
{
if (predicate != null)
{
return context.Set<T>().Where(predicate).SingleOrDefault();
}
else
{
throw new ArgumentNullException("Predicate value is null");
}
}
And call it:
yourContext.GetSingle(g => g.Id == id);
you can use Attributes for this and read the Property which has the right Attribute.
public abstract class MyIdAttribute: Attribute
{
}
public class MyClass
{
[MyId]
WhatEverName {get; set;}
}
and in your Method
public T GetSingle(int id)
{
var propertyInfos = typeof(T).GetProperties().Where(property => property.GetCustomAttributes<MyIdAttribute>().Count() > 0).ToList();
if (propertyInfos.Any())
{
foreach(T current in GetAll())
{
object value = propertyInfos[0].GetValue(current);
if(value == id)
{
return current;
}
}
}
}
Cheers
Thomas
Related
I'm at a lost for how to write a unit test for my web api GET by id method.
Here is what I have:
public void GetProduct_ShouldReturnSameID()
{
var context = new TestModelContext();
context.Products.Add(GetDemoProduct());
var controller = new ProductsController(context);
var result = controller.GetProduct(3) as OkNegotiatedContentResult<Product>;
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Content.Id);
}
And my controller method I'm trying to test
public IHttpActionResult GetProduct(int id)
{
var product = (from t in db.Products.Include(t => t.Reviews)
.Where(t => t.Id == id)
select t);
if (product == null || product.Count() == 0)
{
return NotFound();
}
return Ok(product);
}
My test works find with my other controllers, but just not this one. I was wondering what is wrong with this? My test fails with an
"Expected: not null But was: null"
public class TestModelContext : IModelContext {
public TestModelContext() {
this.Products = new TestProductDbSet();
}
public DbSet<Product> Products { get; set; }
public int SaveChanges() {
return 0;
}
public void MarkAsModified(Product item) { }
public void Dispose() { }
}
public class TestProductDbSet : TestDbSet<Product> {
public override Product Find(params object[] keyValues) {
return this.SingleOrDefault(product => product.Id == (int)keyValues.Single());
}
}
public class TestDbSet<T> : DbSet<T>, IQueryable, IEnumerable<T>
where T : class
{
ObservableCollection<T> _data;
IQueryable _query;
public TestDbSet()
{
_data = new ObservableCollection<T>();
_query = _data.AsQueryable();
}
// ...
public override T Create()
{
return Activator.CreateInstance<T>();
}
public override TDerivedEntity Create<TDerivedEntity>()
{
return Activator.CreateInstance<TDerivedEntity>();
}
public override ObservableCollection<T> Local
{
get { return new ObservableCollection<T>(_data); }
}
Type IQueryable.ElementType
{
get { return _query.ElementType; }
}
System.Linq.Expressions.Expression IQueryable.Expression
{
get { return _query.Expression; }
}
IQueryProvider IQueryable.Provider
{
get { return _query.Provider; }
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _data.GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _data.GetEnumerator();
}
}
GetDemoProduct:
Product GetDemoProduct()
{
return new Product() { Id = 3, Name = "Name", Reviews = null };
}
According to the sample code there is no code path that would result in the method under test returning null.
It's either going to return a NotFoundResult or a OkNegotiatedContentResult<Product>
Given that it is possible for the method under test to return a NotFoundResult , if the if (product == null || product.Count() == 0) condition is met and the method does indeed return not found result, then the following in your test
...as OkNegotiatedContentResult<Product>;
trying to cast NotFoundResult as OkNegotiatedContentResult<Product> will cause the result to be null.
You should recheck your setup/configuration of your TestModelContext as your linq call is causing the product variable to be null which in turn causes the NotFoundResult to be returned.
UPDATE:
Ok was able to start testing it based on your updated details and found an issue i should have noticed earlier.
First I was getting an error when added fake Product to list and had to update the TestDbSet base class to include added entities. I'll assume it was omitted in the sample code.
public override T Add(T entity) {
_data.Add(entity);
return entity;
}
next in the method under test, given the name the method and the expectation in the test, it should be returning a single Product. You were returning the query which would also result in null when you did the cast in the test.
public IHttpActionResult GetProduct(int id) {
var product = (from t in db.Products.Include(t => t.Reviews)
.Where(t => t.Id == id)
select t);
if (product == null || product.Count() == 0) {
return NotFound();
}
return Ok(product.First());
}
When the above two changes were made, the test passed as expected.
It looks like the controller is returning a null as the result. Most likely the Products table and/or the Reviews table does not include a value of 3 that you are passing in as the parameter to your web method.
This is what I suspect. Your GetDemoProduct() method which returns the product you are adding does not have Reviews. Hence, your query:
var product = (from t in db.Products.Include(t => t.Reviews)
.Where(t => t.Id == id)
select t);
did not return any records. Just a thought. If you can show us your GetDemoProduct() then we can tell.
I have two view models, PublishedSong and RadioStation where I want them to have IncrementViews(int id) function.
Instead of copying and pasting the function in to both controllers I wanted to make a generic helper class.
Helper:
public class CustomDBHelper<T>
{
public static IEnumerable<T> GetElements(ApplicationDbContext db, T type)
{
if (type.Equals(typeof(SongsController)))
return (IEnumerable<T>)db.PublishedSongs;
else if (type.Equals(typeof(RadioStationsController)))
return (IEnumerable<T>)db.RadioStations;
else
throw new Exception("Controller not found, DBHelper");
}
}
Controller:
public class MusicBaseController : Controller
{
public JsonResult IncrementViews(int id)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
db.PublishedSongs.Single(x => x.Id == id);
var element = CustomDBHelper<T>.GetElements(db, this.GetType()).Single(x => x.Id == id);
element.UniquePlayCounts++;
db.SaveChanges();
return Json(new { UniquePlayCounts = element.UniquePlayCounts }, JsonRequestBehavior.AllowGet);
}
}
}
I am having trouble with this line: var element = CustomDBHelper<T>.GetElements(db, this.GetType()).Single(x => x.Id == id);
The <T> is invalid. I am new to generics, I think it expects a class but because the class could either be PublishedSong or RadioStation I don't know how to do it.
The following implementation will work for you:
public class CustomDBHelper
{
public static IEnumerable GetElements(ApplicationDbContext db, Type type)
{
if (type.Equals(typeof(SongsController)))
{
return db.PublishedSongs;
}
else if (type.Equals(typeof(RadioStationsController)))
{
return db.RadioStations;
}
else
{
throw new Exception("Controller not found, DBHelper");
}
}
}
And you will need to cast the result of this function to the required type.
On a side note, type generics are used, well, for being type generic. Since you pass the type as a parameter it's not necessary.
I have the following static class:
public static class SortFilter
{
public enum SortDirection { Ascending, Descending }
public static IEnumerable<TEntity> Sort<TEntity, TKey>(IEnumerable<TEntity> entities, Func<TEntity, TKey> sorter, SortDirection d)
{
if (SortDirection.Ascending == d)
{
return entities.OrderBy(sorter);
}
else
{
return entities.OrderByDescending(sorter);
}
}
public static IEnumerable<TEntity> Sort<TEntity>(IEnumerable<TEntity> entities, string sortParams)
{
string[] parameters = sortParams.Split('_');
if (parameters.Count() == 1 || parameters.Count() > 2)
{
return entities;
}
else
{
if (parameters[1] == "ascending")
{
return Sort(entities, x => GetPropertyValue(x, parameters[0]), SortDirection.Ascending);
}
else if (parameters[1] == "descending")
{
return Sort(entities, x => GetPropertyValue(x, parameters[0]), SortDirection.Descending);
}
else
{
return entities;
}
}
}
public static object GetPropertyValue(object obj, string name)
{
return obj == null ? null : obj.GetType()
.GetProperty(name)
.GetValue(obj, null);
}
}
I can call the Sort method on a List like this (the User class has Id and Name properties):
users = SortFilter.Sort(users, "Name_ascending");
users = SortFilter.Sort(users, "Id_ascending");
So far, so good: that will work just fine.
However, let's say my User class also has a UserGroup property and that I want to sort my User list by the Name of that UserGroup. This call will obviously fail:
users = SortFilter.Sort(users, "UserGroup.Name_ascending");
given that UserGroup.Name is not itself a Type (therefore GetPropertyValue method will throw an exception).
Is there a way to make a generic enough Sort function that will take a collection and sort it by any number of nested properties sent as an argument? I have several Views with table data that should be sorted by any column the user clicks, in ascending or descending order. Having sorting and filtering code within the controller seems very dirty.
Like always for string parameters for LINQ use DynamicLINQ:
using System.Linq.Dynamic;
//..
if (parameters[1] == "ascending" || parameters[1] == "descending")
{
return entities.AsQueryable()
.OrderBy(string.Format("{0} {1}", parameters[0], parameters[1]))
}
else
{
return entities;
}
Docs can be found here in LinqSamples/DynamicQuery/Dynamic Expressions.html.
Nested properties are supported of course.
I am currently working through a .NET Web API tutorial located here. In the example, we have an interface defined in a model class like so:
namespace ProductStore.Models
{
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
void Remove(int id);
bool Update(Product item);
}
}
Then, later in the tutorial, we implement this interface like so:
namespace ProductStore.Models
{
public class ProductRepository : IProductRepository
{
private List<Product> products = new List<Product>();
private int _nextId = 1;
public ProductRepository()
{
Add(new Product { Name = "Tomato soup", Category = "Groceries", Price = 1.39M });
Add(new Product { Name = "Yo-yo", Category = "Toys", Price = 3.75M });
Add(new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });
}
public IEnumerable<Product> GetAll()
{
return products;
}
public Product Get(int id)
{
return products.Find(p => p.Id == id);
}
public Product Add(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.Id = _nextId++;
products.Add(item);
return item;
}
public void Remove(int id)
{
products.RemoveAll(p => p.Id == id);
}
public bool Update(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
int index = products.FindIndex(p => p.Id == item.Id);
if (index == -1)
{
return false;
}
products.RemoveAt(index);
products.Add(item);
return true;
}
}
}
My question is, why is the interface written so that GetAll() returns IEnumerable<Product> if the implementation is going to be specifically operating on a List<Product>?
I am assuming this is to facilitate reuse so that some other IProductRepository implementation could use a different IEnumerable<Product> (though an example of this would be nice, because I can't think of one, not that I doubt it exists, I'm just not ultra experienced).
Assuming reuse is the goal indeed, then why is the implementation written like this:
public IEnumerable<Product> GetAll()
{
return products;
}
Instead of like this:
public List<Product> GetAll()
{
return products;
}
Does the framework or compiler not have the ability to see that public List<Product> GetAll() is derivable from public IEnumerable<Product> GetAll()?
Two main reasons:
this hides the actual implementation so that the consumer doesn't do anything they shouldn't with the data (e.g. add or remove items directly from the list). Obviously, the consumer can cast the result to List<T>, but they would be relying on an undocumented implementation detail, so if you change it later and it breaks their code, it will be their fault.
if someday you need to change the implementation to use something other than a List<T>, you can do it without any visible change for the consumer.
You want changes to your List<T> to operate through your repository methods and not give the user direct access to the List<T> - thus, you return an IEnumerable<T> so that they cannot change the underlying collection
I am looking a way to create Generic GetById that get params object[] as parameter, knows to find the key/s field/s and know to find the relevant entity.
In the way to find a solution I thought on a generic method that returns the PK fields definition and a generic method that can return the entity based on fields.
I am looking for something I can use in table with one or more fields as primary key.
EDIT
one or more fields as primary key example =
table Customers have (CompanyId, CustomerName, Address, CreateDate).
The primary key of Customers are CompanyId are CustomerName.
I am looking for generic GetById that will know to handle also those such of tables.
You can't get "generic" approach if you don't know how many members is in the key and what types do they have. I modified my solution for single key to multiple keys but as you can see it is not generic - it uses order in which keys are defined:
// Base repository class for entity with any complex key
public abstract class RepositoryBase<TEntity> where TEntity : class
{
private readonly string _entitySetName;
private readonly string[] _keyNames;
protected ObjectContext Context { get; private set; }
protected ObjectSet<TEntity> ObjectSet { get; private set; }
protected RepositoryBase(ObjectContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
Context = context;
ObjectSet = context.CreateObjectSet<TEntity>();
// Get entity set for current entity type
var entitySet = ObjectSet.EntitySet;
// Build full name of entity set for current entity type
_entitySetName = context.DefaultContainerName + "." + entitySet.Name;
// Get name of the entity's key properties
_keyNames = entitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
}
public virtual TEntity GetByKey(params object[] keys)
{
if (keys.Length != _keyNames.Length)
{
throw new ArgumentException("Invalid number of key members");
}
// Merge key names and values by its order in array
var keyPairs = _keyNames.Zip(keys, (keyName, keyValue) =>
new KeyValuePair<string, object>(keyName, keyValue));
// Build entity key
var entityKey = new EntityKey(_entitySetName, keyPairs);
// Query first current state manager and if entity is not found query database!!!
return (TEntity)Context.GetObjectByKey(entityKey);
}
// Rest of repository implementation
}
I don't know how useful this would be because it is generic but you could do this:
public TEntity GetById<TEntity>(params Expression<Func<TEntity, bool>>[] keys) where TEntity : class
{
if (keys == null)
return default(TEntity);
var table = context.CreateObjectSet<TEntity>();
IQueryable<TEntity> query = null;
foreach (var item in keys)
{
if (query == null)
query = table.Where(item);
else
query = query.Where(item);
}
return query.FirstOrDefault();
}
and then you could call it like this:
var result = this.GetById<MyEntity>(a => a.EntityProperty1 == 2, a => a.EntityProperty2 == DateTime.Now);
Disclaimer: this really isn't a GetByid, it's really a "let me give you a couple parameters and give me the first entity that matches". But that being said, it uses generics and it will return an entity if there is a match and you search based on primary keys.
I think you can't implement such thing because you won't be able to join between each passed value with the appropriate key field.
I'd suggest using custom method for each entity:
Assuming Code and Name are keys in Person table:
public IEnumerable<Person> ReadById(int code, string name)
{
using (var entities = new Entities())
return entities.Persons.Where(p => p.Code = code && p.Name = name);
}
Ok this is my second stab at it. I think this would work for you.
public static class QueryExtensions
{
public static Customer GetByKey(this IQueryable<Customer> query, int customerId,string customerName)
{
return query.FirstOrDefault(a => a.CustomerId == customerId && a.CustomerName == customerName);
}
}
So the beauty behind this extension method is you can now do this:
Customer customer = Db.Customers.GetByKey(1,"myname");
You obviously have to do this for every type, but probably worth it if you need it :)
I think the set up is a bit but I do think creating a reusable pattern will pay off in the long run. I just wrote this up and haven't tested, but I based off a searching pattern I use a lot.
Required Interfaces:
public interface IKeyContainer<T>
{
Expression<Func<T, bool>> GetKey();
}
public interface IGetService<T>
{
T GetByKey(IKeyContainer<T> key);
}
Example Entities:
public class Foo
{
public int Id { get; set; }
}
public class ComplexFoo
{
public int Key1 { get; set; }
public int Key2 { get; set; }
}
Implementation Example:
public class FooKeyContainer : IKeyContainer<Foo>
{
private readonly int _id;
public FooKeyContainer(int id)
{
_id = id;
}
public Expression<Func<Foo, bool>> GetKey()
{
Expression<Func<Foo, bool>> key = x => x.Id == _id;
return key;
}
}
public class ComplexFooKeyContainer : IKeyContainer<ComplexFoo>
{
private readonly int _id;
private readonly int _id2;
public ComplexFooKeyContainer(int id, int id2)
{
_id = id;
_id2 = id2;
}
public Expression<Func<ComplexFoo, bool>> GetKey()
{
Expression<Func<ComplexFoo, bool>> key = x => x.Key1 == _id && x.Key2 == _id2;
return key;
}
}
public class ComplexFooService : IGetService<ComplexFoo>
{
public ComplexFoo GetByKey(IKeyContainer<ComplexFoo> key)
{
var entities = new List<ComplexFoo>();
return entities.Where(key.GetKey()).FirstOrDefault();
}
}
Usage:
var complexFoo = ComplexFooService.GetByKey(new ComplexFooKeyContainer(1, 2));