Changing selected objects inside a query - c#

I have a class that needs a property set inside a LINQ-to-SQL query. My first attempt was to have a "setter" method that would return the object instance and could be used in my select, like this:
public partial class Foo
{
public DateTime RetrievalTime { get; set; }
public Foo SetRetrievalTimeAndReturnSelf ( DateTime value )
{
RetrievalTime = value;
return this;
}
}
....
from foo in DataContext.GetTable<Foo> select foo.SetRetrievalTimeAndReturnSelf();
Unfortunately, such a query throws an exception like this: "System.NotSupportedException: Method 'Foo.SetRetrievalTime(System.DateTime)' has no supported translation to SQL".
Is there any alternative to converting the result to a list and iterating over it? The query is used in a custom "Get" method that wraps the DataContext.GetTable method, so will be used as the base for many other queries. Immediately converting a potentially-large result set to a list would not be optimal.
UPDATE
Here's a better example of what I'm trying to do, updated with Jason's proposed solution:
protected IQueryable<T> Get<T>() where T : class, ISecurable
{
// retrieve all T records and associated security records
var query = from entity in DataContext.GetTable<T> ()
from userEntityAccess in DataContext.GetTable<UserEntityAccess> ()
where userEntityAccess.SysUserId == CurrentUser.Id
&& entity.Id == userEntityAccess.EntityId
&& userEntityAccess.EntityClassName == typeof ( T ).Name
select new { entity, userEntityAccess };
return query.AsEnumerable ()
.Select ( item =>
{
item.entity.CanRead = item.userEntityAccess.CanRead;
item.entity.CanWrite = item.userEntityAccess.CanWrite;
item.entity.CanDelete = item.userEntityAccess.CanDelete;
return item.entity;
} ).AsQueryable ();
}
public interface ISecurable
{
int Id { get; set; }
bool CanRead { get; set; }
bool CanWrite { get; set; }
bool CanDelete { get; set; }
}
UserEntityAccess is a cross-reference table between a user and a business object record (i.e. an entity). Each record contains fields like "CanRead", "CanWrite", and "CanDelete", and determines what a specific user can do with a specific record.
ISecurable is a marker interface that must be implemented by any LINQ-to-SQL domain class that needs to use this secured Get method.

var projection = DataContext.GetTable<Foo>
.AsEnumerable()
.Select(f => f.SetRetrievalTimeAndReturnSelf());
This will then perform the invocation of SetRetrievalTimeAndReturnSelf for each instance of Foo in DataContext.GetTable<Foo> when the IEnumerable<Foo> projection is iterated over.
What do you need to know the time that object was yanked of the database for? That's potentially smelly.

Related

DbSet variable table name

I am writing an application where I need to abstract the DbSet table name.
Instead of calling _db.Activities.ToList() (where Activity is a table in Sql) the code below will work for any variable table input.
Now I wanted to use .Where(),.OrderBy(),.FromSqlRaw() and other methods on top of the existing code.
How can I write _db.Activities.FromSqlRaw(...) for example, with a variable table name, just like it is doing for the GetAll method.
This is my DbSet for Activity
public virtual DbSet<Activity> Activities { get; set; } = null!;
This is the method to get all records from a variable table
public dynamic GetAll(string Table)
{
var curEntityPI = _db.GetType().GetProperty(Table);
var curEntityType = curEntityPI.PropertyType.GetGenericArguments().First();
// Getting Set<T> method
var method = _db.GetType().GetMember("Set").Cast<MethodInfo>().Where(x => x.IsGenericMethodDefinition).FirstOrDefault();
// Making Set<SomeRealCrmObject>() method
var genericMethod = method.MakeGenericMethod(curEntityType);
// invoking Setmethod into invokeSet
dynamic invokeSet = genericMethod.Invoke(_db, null);
// invoking ToList method from Set<> invokeSet
return Enumerable.ToList(invokeSet);
}
The general idea comes from this post
reflection-linq-dbset
Define return type of method as List< dynamic> instead of dynamic
public List<dynamic> GetAll(string Table)
{
//your code...
return Enumerable.ToList(invokeSet);
}
Activity Class:
public class Activity
{
public int Field1 { get; set; }
public string Field2 { get; set; }
}
So, you can use all methods of List type
var activityList = GetAll("Activities");
var filteredList = activities.Where(x => x.Field1 > 1);
var orderedList = filteredList.OrderBy(x => x.Field2);

LINQ join based in interface implemation

Let's say I have a an interface, which is basically a combination of two sub-interfaces. The idea behind this is, that I have two different API's. One which provides public information on a person. And once which provides the 'secret' information. It could look something like this:
public interface IPublicPersonData
{
// The ID is the key
int PersonId { get; set; }
// This property is specific to this part
string Name {get; set; }
}
public interface ISecretPersonData
{
// The ID is the key
int PersonId { get; set; }
// This property is specific to this part
decimal AnnualSalary{ get; set; }
}
public interface IPerson: IPublicPersonData, ISecretPersonData
{
// No new stuff, this is merely a combination of the two.
}
So basically I get two lists. One List<IPublicPersonData> and one List<ISecretPersonData>. I would like to join these into a single List<IPerson>, ideally using LINQ.
I cannot really find anything on how control the type of output from LINQ, based on the type of input, even if the logic is there (in the means of interfaces implementing interfaces).
public List<IPerson> JoinPersonData(
List<IPublicPersonData> publicData,
List<ISecretPersonData> secretData)
{
// What the heck goes here?
}
Say you wrote a method such as:
public ISomething CombinePersonWithSecret(
IPublicPersonData publicPerson,
ISecretPersonData secret)
{
if(publicPerson.PersonId != secret.PersonId)
{
throw ...;
}
//join 2 params into a single entity
return something;
}
Now you might...
IEnumerable<ISomething> secretivePeople = PublicPeople.Join(
SecretPersonData,
publicPerson => publicPerson.PersonId,
secret => secret.PersonId,
(publicPerson, secret) => CombinePersonWithSecret(publicPerson, secret))
The problem is not in the Join, it is in the IPerson you want to return. One of the parameters of the Join methods is used what to do with joined result.
You want to join them into a new object that implements IPerson. If you already have such an object: great, use that one, if you don't have it, here is an easy one:
public PersonData : IPerson // and thus also IPublicPersonData and ISecretPersonData
{
// this PersonData contains both public and secret data:
public IPublicPersonData PublicPersonData {get; set;}
public ISecretPersnData SecretPersonData {get; set;}
// implementation of IPerson / IPublicPersonData / ISecretPersonData
int PersonId
{
get {return this.PublicPersonData.Id; }
set
{ // update both Ids
this.PublicPersonData.Id = value;
this.SecreatPersonData.Id = value;
}
}
public string Name
{
get { return this.PublicPersonData.Name; },
set {this.PublicPersonData.Name = value;}
}
public decimal AnnualSalary
{
get {return this.SecretPersonData.AnnualSalary;},
set {this.SecretPersnData.AnnualSalary = value;
}
}
This object requires no copying of the values of the puclic and secret person data. Keep in mind however, if you change values, the original data is changed. If you don't want this, you'll need to copy the data when creating the object
IEnumerable<IPublicPersonData> publicData = ...
IEnumerable<ISecretPersonData> secretData = ...
// Join these two sequences on same Id. Return as an IPerson
IEnumerable<IPerson> joinedPerson = publicData // take the public data
.Join(secretData, // inner join with secret data
publicPerson => publicPerson.Id, // from every public data take the Id
secretPerson => secretPerson.Id, // from every secret data take the Id
(publicPerson, secretPerson) => new PersonData() // when they match make a new PersonData
{
PublicPersonData = publicPerson,
SecretPersnData = secretPerson,
});
LINQ's Join method does the job for you. Assuming there is a Person : IPerson class, here is two ways to implement your JoinPersonData method:
public static IEnumerable<IPerson> LiteralJoinPersonData(List<IPublicPersonData> publics, List<ISecretPersonData> secrets)
{
return from p in publics
join s in secrets on p.PersonId equals s.PersonId
select new Person(p.PersonId, p.Name, s.AnnualSalary);
}
public static IEnumerable<IPerson> FunctionalJoinPersonData(List<IPublicPersonData> publics, List<ISecretPersonData> secrets)
{
return publics
.Join<IPublicPersonData, ISecretPersonData, int, IPerson>(
secrets,
p => p.PersonId,
s => s.PersonId,
(p, s) => new Person(p.PersonId, p.Name, s.AnnualSalary));
}

How to use a copy-constructor in a LINQ to Entities query?

I'm working on a Linq expression in which I get an object from a DBContext, and I want to make it a custom ViewModel object
my ViewModel receives as parameter an object obtained from the DBContext to work the information and return it completely
This is a little example
public class Obj1 // Object i get from database
{
public int id { get; set; }
public string Param { get; set; }
public string Param2 { get; set; }
public string Random { get; set; }
}
public class Obj2 //ViewModel
{
public string ParamFormateado { get; set; }
public string Random { get; set; }
public Obj2(Obj1 parametro)
{
ParamFormateado = parametro.Param + parametro.Param2;
Random = parametro.Random;
}
}
What I'm trying to do is get an Obj2 with a Linq expression who returns an Obj1 without transforming the information in the linq expression, since in my case it becomes a basically illegible expression
I was try something like this
Obj2 objeto = db.Obj1.Where(x => x.id == "0").Select(x => new Obj2(x)).FirstOrDefault();
Is it possible to perform a Linq query similar to the one I am proposing? since otherwise, I end up having extremely long Linq expressions to format this information, but what would be the best alternative in these cases?
You can't do that because only parameterless constructors are supported. But you can do it with Linq-To-Objects which can be forced with AsEnumerable:
Obj2 objeto = db.Obj1
.Where(x => x.id == "0")
.AsEnumerable() // <--- here
.Select(x => new Obj2(x))
.FirstOrDefault();
So only the filter with Where will be executed in the database, the remaining record(s) are processed in-process.
https://codeblog.jonskeet.uk/2011/01/14/reimplementing-linq-to-objects-part-36-asenumerable/
Dont do it with Linq like that. you have to create a method that takes obj1 as parameter, maps properties and then returns obj2. Or use Automapper from nuget repository.
do it like this
public obj2 Map(obj1 source)
{
var destination = new obj2();
destination.param1 = source.param1;
//
return destination;
}
if you want to pass a collection of objects then do just that and just foreach through the list and return a list of mapped objects. But i would advise you to use Automapper since it automates the proces and you dont have to write a long mapping code.

Is there a way of comparing all the values within 2 entities?

I'm using EF4.3 so I'm referring to entities, however it could apply to any class containing properties.
I'm trying to figure out if its possible to compare 2 entities. Each entity has properties that are assigned values for clarity let say the entity is 'Customer'.
public partial class Customer
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
...
...
}
The customer visits my website and types in some details 'TypedCustomer'. I check this against the database and if some of the data matches, I return a record from the database 'StoredCustomer'.
So at this point I've identified that its the same customer returning but I wan't to valid the rest of the data. I could check each property one by one, but there are a fair few to check. Is it possible to make this comparison at a higher level which takes into account the current values of each?
if(TypedCustomer == StoredCustomer)
{
.... do something
}
If you're storing these things in the database, it is logical to assume you'd also have a primary key called something like Id.
public partial class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
...
...
}
Then all you do is:
if(TypedCustomer.Id == StoredCustomer.Id)
{
}
UPDATE:
In my project, I have a comparer for these circumstances:
public sealed class POCOComparer<TPOCO> : IEqualityComparer<TPOCO> where TPOCO : class
{
public bool Equals(TPOCO poco1, TPOCO poco2)
{
if (poco1 != null && poco2 != null)
{
bool areSame = true;
foreach(var property in typeof(TPOCO).GetPublicProperties())
{
object v1 = property.GetValue(poco1, null);
object v2 = property.GetValue(poco2, null);
if (!object.Equals(v1, v2))
{
areSame = false;
break;
}
});
return areSame;
}
return poco1 == poco2;
} // eo Equals
public int GetHashCode(TPOCO poco)
{
int hash = 0;
foreach(var property in typeof(TPOCO).GetPublicProperties())
{
object val = property.GetValue(poco, null);
hash += (val == null ? 0 : val.GetHashCode());
});
return hash;
} // eo GetHashCode
} // eo class POCOComparer
Uses an extension method:
public static partial class TypeExtensionMethods
{
public static PropertyInfo[] GetPublicProperties(this Type self)
{
self.ThrowIfDefault("self");
return self.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where((property) => property.GetIndexParameters().Length == 0 && property.CanRead && property.CanWrite).ToArray();
} // eo GetPublicProperties
} // eo class TypeExtensionMethods
Most simple seems to use reflexion : get the properties and/or fields you want to compare, and loop through them to compare your two objects.
This will be done with getType(Customer).getProperties and getType(Customer).getFields, then using getValue on each field/property and comparing.
You might want to add custom informations to your fields/properties to define the ones that needs
comparing. This could be done by defining a AttributeUsageAttribute, that would inherit from FlagsAttribute for instance. You'll then have to retrieve and handle those attributes in your isEqualTo method.
I don't think there's much of a purpose to checking the entire object in this scenario - they'd have to type every property in perfectly exactly as they did before, and a simple "do they match" doesn't really tell you a lot. But assuming that's what you want, I can see a few ways of doing this:
1) Just bite the bullet and compare each field. You can do this by overriding the bool Equals method, or IEquatable<T>.Equals, or just with a custom method.
2) Reflection, looping through the properties - simple if your properties are simple data fields, but more complex if you've got complex types to worry about.
foreach (var prop in typeof(Customer).GetProperties()) {
// needs better property and value validation
bool propertyMatches = prop.GetValue(cust1, null)
.Equals(prop.GetValue(cust2, null));
}
3) Serialization - serialize both objects to XML or JSON, and compare the strings.
// JSON.NET
string s1 = JsonConvert.SerializeObject(cust1);
string s2 = JsonConvert.SerializeObject(cust2);
bool match = s1 == s2;

C# Select clause returns system exception instead of relevant object

I am trying to use the select clause to pick out an object which matches a specified name field from a database query as follows:
objectQuery = from obj in objectList
where obj.Equals(objectName)
select obj;
In the results view of my query, I get:
base {System.SystemException} = {"Boolean Equals(System.Object)"}
Where I should be expecting something like a Car, Make, or Model
Would someone please explain what I am doing wrong here?
The method in question can be seen here:
// this function searches the database's table for a single object that matches the 'Name' property with 'objectName'
public static T Read<T>(string objectName) where T : IEquatable<T>
{
using (ISession session = NHibernateHelper.OpenSession())
{
IQueryable<T> objectList = session.Query<T>(); // pull (query) all the objects from the table in the database
int count = objectList.Count(); // return the number of objects in the table
// alternative: int count = makeList.Count<T>();
IQueryable<T> objectQuery = null; // create a reference for our queryable list of objects
T foundObject = default(T); // create an object reference for our found object
if (count > 0)
{
// give me all objects that have a name that matches 'objectName' and store them in 'objectQuery'
objectQuery = from obj in objectList
where obj.Equals(objectName)
select obj;
// make sure that 'objectQuery' has only one object in it
try
{
foundObject = (T)objectQuery.Single();
}
catch
{
return default(T);
}
// output some information to the console (output screen)
Console.WriteLine("Read Make: " + foundObject.ToString());
}
// pass the reference of the found object on to whoever asked for it
return foundObject;
}
}
Note that I am using the interface "IQuatable<T>" in my method descriptor.
An example of the classes I am trying to pull from the database is:
public class Make: IEquatable<Make>
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Model> Models { get; set; }
public Make()
{
// this public no-argument constructor is required for NHibernate
}
public Make(string makeName)
{
this.Name = makeName;
}
public override string ToString()
{
return Name;
}
// Implementation of IEquatable<T> interface
public virtual bool Equals(Make make)
{
if (this.Id == make.Id)
{
return true;
}
else
{
return false;
}
}
// Implementation of IEquatable<T> interface
public virtual bool Equals(String name)
{
if (this.Name.Equals(name))
{
return true;
}
else
{
return false;
}
}
}
And the interface is described simply as:
public interface IEquatable<T>
{
bool Equals(T obj);
}
IQueryable<T> executes your query against the backing data store (in this case, it's SQL RDBMS). Your SQL RDBMS has no idea of IEquatable<T>*, and cannot use its implementation: the query function must be translatable to SQL, and obj.Equals(objectName) is not translatable.
You can convert IQueryable<T> to IEnumerable<T> and do the query in memory, but that would be too inefficient. You should change the signature to take a Expression<Func<TSource, bool>> predicate, and pass the name checker to it:
public static T Read<T>(Expression<Func<T,bool>> pred) {
using (ISession session = NHibernateHelper.OpenSession()) {
return session.Query<T>().SingleOrdefault(pred);
}
}
You can now use this method as follows:
Make snake = Read<Make>(x => x.Name == "snake");
* Additionally, your IEquatable<T> is not used in the method that you are showing: the Equals(string) method would qualify as an implementation of IEquatable<string>, but it is not mentioned in the list of interfaces implemented by your Make class.
One of your calls to the Equal override could be throwing an exception.
For debugging purposes, try iterating rather than using Linq and you should find out which one:
foreach(object obj in objectList)
{
bool check = obj.Equals(objectName) // set a breakpoint here
}
As far as what is causing the exception, ensure that each of your object Name and Id properties have values.

Categories