I have 2 classes User and UserDto both have a Phones property, all the other properties I can map perfectly.
But the problem occurs with the Phones list of the User class, since being null, I cannot identify what type of list it is.
What I need is to be able to and create a list based on its type using reflection.
var list = new List<PhoneDto>();
list.Add(new PhoneDto { Code = 1, Number = 11111111 });
list.Add(new PhoneDto { Code = 2, Number = 11111112 });
list.Add(new PhoneDto { Code = 3, Number = 11111113 });
list.Add(new PhoneDto { Code = 4, Number = 11111114 });
list.Add(new PhoneDto { Code = 5, Number = 11111115 });
var userDto=new UserDto
{
Age=18,
IsData=true,
CreationDate=DateTime.Now,
Phones =list
};
var myMapper = new MyMapper();
var user= myMapper.Map<User>(userDto);
public class User
{
public string Name { get; set; }
public DateTime CreationDate { get; set; }
public int Age { get; set; }
public bool IsData { get; set; }
public ICollection.Phone. Phones { get; set; }
}
public class UserDto
{
public string Name { get; set; }
public DateTime CreationDate { get; set; }
public int Age { get; set; }
public bool IsData { get; set; }
public List.PhoneDto. Phones { get; set; }
}
namespace CustomMapping;
public class MyMapper
{
public T Map<T>(object sourceObject)
{
if (sourceObject == null) throw new Exception("Source object is null");
var instance = Activator.CreateInstance(typeof(T));
if (instance == null) throw new Exception("Can not create de typeof(T) Instance");
var sourceType = sourceObject.GetType();
var targetType = instance.GetType();
PropertyInfo[] sourceProperties = sourceType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] targetProperties = targetType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var sourceProperty in sourceProperties)
{
if (sourceProperty == null) continue;
var targetProperty = targetProperties.FirstOrDefault(p => p.Name.ToLower() == sourceProperty.Name.ToLower() && p.CanWrite);
if (targetProperty == null) continue;
var sourceValue = sourceProperty?.GetValue(sourceObject, null);
if (sourceProperty?.PropertyType == targetProperty.PropertyType)
{
instance?.GetType()?.GetProperty(sourceProperty.Name)?.SetValue(instance, sourceValue);
continue;
}
var isEnumerable = IsEnumerable(targetProperty);
if (isEnumerable)
{
//---------Here I need to map the lists---------
}
}
return (T)instance;
}
private bool IsEnumerable(PropertyInfo propertyInfo)
{
return (propertyInfo.PropertyType.GetInterfaces().Any(p => p.Name == "IEnumerable`1") && propertyInfo.PropertyType.FullName.IndexOf("System.String") < 0);
}
}
I would appreciate any help.
Related
I want to write a function which it turns every properies and child properties of an object. And if all properties of one property are null, then I will set that property as null. I will explain with one example.
For example, if both TeacherName and TeacherSurname are null then I want to set Teacher to null. Then, if ExamMark and ExamName and Teacher are null, then Exam will be null.
You can see json version of like my question from this link Json Version
public class Student
{
public string Name { get; set; }
public string Surname { get; set; }
public Address Address { get; set; }
public Exam Exam { get; set; }
}
public class Exam
{
public string ExamMark { get; set; }
public string ExamName { get; set; }
public Teacher Teacher { get; set; }
}
public class Teacher
{
public string TeacherName { get; set; }
public string TeacherSurname { get; set; }
}
public class Address
{
public string Country { get; set; }
public string City { get; set; }
}
I wrote this method. But this doing only first step. But I need recursive for child class. How can I convert this method to recursive?
public static object ConvertToNull(object obj)
{
Type objType = obj.GetType();
PropertyInfo[] properties = objType.GetProperties();
var mainClassProperties = properties.Where(p => p.PropertyType.Assembly == objType.Assembly);
foreach (var mainClassProperty in mainClassProperties)
{
object propValue = mainClassProperty.GetValue(obj, null);
var classAllProperties = propValue.GetType().GetProperties();
if (propValue.GetType().GetProperties().All(propertyInfo => propertyInfo.GetValue(propValue) == null))
{
mainClassProperty.SetValue(obj, null);
}
}
return obj;
}
What you're asking for is actually an anti-pattern. What this does is it propagates the requirement for tons of null checks in your code. Not only do you have to check if all properties are null, you also have to check if your object is null when you want to use it. Also reflection is very slow and if you're doing this often, you'll bog down your application.
You should look into the Null Object Pattern. It basically does what you want it to, and you remove all those pesky null checks:
public class Student
{
public string Name { get; set; }
public string Surname { get; set; }
public Address Address { get; set; }
public Exam Exam { get; set; }
public static Student NullStudent { get; } = new Student
{
Name = null,
Surname = null,
Address = Address.NullAddress,
Exam = Exam.NullExam,
}
}
You can do this for each object in your code that acts this way (you can see that I did it on your nested Address and Exam types as well) and then instead of doing this:
if (Student.EverythingIsNull) { Student = null }
if (Student is null) { //do null stuff }
You can do this:
if (item == Student.NullStudent) { //do null stuff }
This leads to clearer code, your intent stands out more, and you can specifically define in each object what constitutes as null.
using Generics and Reflection.
public T ConvertToNull<T>(T model) where T : class
{
if (model == null) return null;
Type type = model.GetType();
PropertyInfo[] properties = type.GetProperties();
var valueTypes = properties.Where(p => p.PropertyType.Assembly != type.Assembly);
var nonValueTypes = properties.Where(p => p.PropertyType.Assembly == type.Assembly);
foreach (var nonValueType in nonValueTypes)
nonValueType.SetValue(model, ConvertToNull(nonValueType.GetValue(model)));
if (valueTypes.All(z => z.GetValue(model) == null) && nonValueTypes.All(z => z.GetValue(model) == null))
return null;
else
return model;
}
Here you can call it
List<Student> students = new List<Student>();
Student student = new Student() { Name = "StudentName", Surname = "StudentSurname", Address = new Address() { City = "City", Country = "Country" }, Exam = new Exam() { ExamMark = "ExamMark", ExamName = "ExamName", Teacher = new Teacher() { TeacherName = "TeacherName", TeacherSurname = "TeacherSurname" } } };
Student student2 = new Student() { Name = "StudentName", Surname = "StudentSurname", Address = new Address(), Exam = new Exam() { ExamMark = "ExamMark", ExamName = "ExamName", Teacher = new Teacher() } };
students.Add(student);
students.Add(student2);
List<Student> results = new List<Student>();
foreach (var item in students)
{
var result = ConvertToNull(item);
results.Add(result);
}
Have a look at this The GetValueOrNull should work and do what you need, not tested with all possible use cases but it oculd be tweaked a little if doesn't work in all cases
public static bool IsSimpleType(Type type)
{
return
type.IsPrimitive ||
new Type[] {
typeof(Enum),
typeof(String),
typeof(Decimal),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(Guid)
}.Contains(type) ||
Convert.GetTypeCode(type) != TypeCode.Object ||
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>) && IsSimpleType(type.GetGenericArguments()[0]))
;
}
public object GetValueOrNull(object obj)
{
if (obj == null) return null;
Type objType = obj.GetType();
PropertyInfo[] properties = objType.GetProperties();
var simpleTypes = properties.Where(t => IsSimpleType(t.PropertyType));
var nonValueTypes = properties.Where(p => !simpleTypes.Contains(p));
foreach (var child in nonValueTypes)
{
child.SetValue(obj, GetValueOrNull(child.GetValue(obj)));
}
return simpleTypes.All(z => z.GetValue(obj) == null) && nonValueTypes.All(z => z.GetValue(obj) == null) ? null : obj;
}
call it as follows
var student = new Student { Address = new Address { }, Exam = new Exam { Teacher = new Teacher() } };
var test = GetValueOrNull(student);
hope it helps :)
I have an MVC application with EF6. Is there a way to automatically set all properties of a model to [Required]? Some of our models are large with all required fields. Any way to save lines of code or make this cleaner?
public class Employee{
[Required]
public string Name { get; set; }
[Required]
public string Address 1 { get; set; }
[Required]
public string Address 2 { get; set; }
[Required]
public int SSN { get; set; }
[Required]
public double PayRate { get; set; }
[Required]
public int PayType { get; set; }
[Required]
public string JobTitle { get; set; }
[Required]
public bool FullTime { get; set; }
[Required]
public string Sex { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Name { get; set; }
}
Thanks
You can MakeStringColumnsRequired or MakeAllNullableColumnsRequired by means of Fluent API and "dynamic" Expressions:
protected void MakeStringColumnsRequired<T>(DbModelBuilder modelBuilder)
where T : class
{
var type = typeof(T);
foreach (var prop in type.GetProperties().Where(x => x.PropertyType == typeof(string)))
{
var argParam = Expression.Parameter(type, "x");
var nameProperty = Expression.Property(argParam, prop.Name);
var lambda = Expression.Lambda<Func<T, string>>(nameProperty, argParam);
modelBuilder.Entity<T>().Property(lambda).IsRequired();
}
}
protected void MakeAllNullableColumnsRequired<T>(DbModelBuilder modelBuilder)
where T : class
{
var type = typeof(T);
foreach (var prop in type.GetProperties()
.Where(x => Nullable.GetUnderlyingType(x.PropertyType) != null || x.PropertyType == typeof(string))
)
{
var argParam = Expression.Parameter(type, "x");
var nameProperty = Expression.Property(argParam, prop.Name);
var funcType = typeof(Func<,>);
funcType = funcType.MakeGenericType(typeof(T), prop.PropertyType);
var lambdaMethod = typeof(Expression).GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(x => x.Name == "Lambda" && x.IsGenericMethod).First();
lambdaMethod = lambdaMethod.MakeGenericMethod(funcType);
var lambda = lambdaMethod.Invoke(null, new object[] { nameProperty, new ParameterExpression[] { argParam } });
var entity = modelBuilder.Entity<T>();
var entityPropertyMethods = entity.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.Name == "Property" && !x.IsGenericMethod).ToList();
var entityPropertyMethod = entityPropertyMethods
.Where(x => x.GetParameters().First().ParameterType.GetGenericArguments().First().GetGenericArguments().Last() == prop.PropertyType)
.FirstOrDefault();
if(entityPropertyMethod == null)
{
entityPropertyMethod = entity.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.Name == "Property" && x.IsGenericMethod).Last();
entityPropertyMethod = entityPropertyMethod.MakeGenericMethod(Nullable.GetUnderlyingType(prop.PropertyType));
}
var property = entityPropertyMethod.Invoke(entity, new object[] { lambda });
var isRequired = property.GetType().GetMethod("IsRequired");
isRequired.Invoke(property, null);
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
#if StringColumnsRequired
MakeStringColumnsRequired<Employee>(modelBuilder);
#else
MakeAllNullableColumnsRequired<Employee>(modelBuilder)
#endif
}
I have created a method which will create dynamic object list from an object list according to property list. In this case I have completed such task using Expandoobject. But I have failed to create distinct list of such expando object list. Please visit the following fidder and see my code.
public class Program
{
public static void Main()
{
var _dynamicObjectList = new List<Student>();
for (int i = 0; i < 5; i++)
{
_dynamicObjectList.Add(new Student { ID = i, Name = "stu" + i, Address = "address" + i, AdmissionDate = DateTime.Now.AddDays(i) , Age=15, FatherName="Jamal"+i, MotherName = "Jamila"+i});
}
//create again for checking distinct list
for (int i = 0; i < 5; i++)
{
_dynamicObjectList.Add(new Student { ID = i, Name = "stu" + i, Address = "address" + i, AdmissionDate = DateTime.Now.AddDays(i), Age = 15, FatherName = "Jamal" + i, MotherName = "Jamila" + i });
}
// var returnList = test2.GetDdlData<Object>(_dynamicObjectList, "ID,Name,Address");
// var returnList = test2.GetDdlData<Object>(_dynamicObjectList, "ID,FatherName,Address");
var returnList = test2.GetDdlData<Object>(_dynamicObjectList, "ID,Name,FatherName,MotherName,Age");
string strSerializeData = JsonConvert.SerializeObject(returnList);
Console.WriteLine(strSerializeData);
Console.ReadLine();
}
}
public class Student
{
public int? ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public DateTime AdmissionDate { get; set; }
public string FatherName { get; set; }
public string MotherName { get; set; }
public int Age { get; set; }
}
public static class test2
{
public static IList GetDdlData<T>(this IEnumerable<T> source, string userParams)
{
try
{
List<string> otherProperties = userParams.Split(',').ToList();
Dictionary<string, PropertyInfo> parentPropertyInfo = new Dictionary<string, PropertyInfo>();
Dictionary<string, Type> parentType = new Dictionary<string, Type>();
var dynamicObjectList = (from k in source select k).ToList();
if (dynamicObjectList.Count() > 0)
{
//if parentField exists then system will handle parent property
if (otherProperties.Count > 0)
{
foreach (string otherProperty in otherProperties)
{
//get parent field property info
PropertyInfo _info = dynamicObjectList[0].GetType().GetProperty(otherProperty);
parentPropertyInfo.Add(otherProperty, _info);
//get parent field propertyType
Type pType = Nullable.GetUnderlyingType(_info.PropertyType) ?? _info.PropertyType;
parentType.Add(otherProperty, pType);
}
}
}
//return List
IList<object> objList = new List<object>();
foreach (T obj in source)
{
var dynamicObj = new ExpandoObject() as IDictionary<string, Object>;
foreach (string otherProperty in otherProperties)
{
PropertyInfo objPropertyInfo = parentPropertyInfo.FirstOrDefault(m => m.Key == otherProperty).Value;
Type objPropertyType = parentType.FirstOrDefault(m => m.Key == otherProperty).Value;
Object data = (objPropertyInfo.GetValue(obj, null) == null) ? null : Convert.ChangeType(objPropertyInfo.GetValue(obj, null), objPropertyType, null);
dynamicObj.Add(otherProperty, data);
}
objList.Add(dynamicObj);
}
var returnUniqList = objList.Distinct().ToList();
return returnUniqList;
}
catch (Exception ex)
{
throw ex;
}
}
}
https://dotnetfiddle.net/hCuJwD
Just add the following code in the code block.
foreach(var objTemp in objList) {
bool isNotSimilar = true;
foreach(string property in otherProperties) {
//get sending object property data
object tempFValue = (objTemp as IDictionary < string, Object > )[property];
//get current object property data
object tempCValue = (dynamicObj as IDictionary < string, Object > )[property];
if (!tempFValue.Equals(tempCValue)) {
isNotSimilar = false;
break;
}
}
if (isNotSimilar) {
isDuplicate = true;
break;
}
}
DOTNETFIDDLE
In database I have two tables:
public partial class PersonOne
{
public int id { get; set; }
public string name { get; set; }
public string surname { get; set; }
}
public partial class PersonTwo
{
public int id { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
}
I would like to fill my set:
public class PersonOnePersonTwo
{
public int PersonOneId { get; set; }
public int PersonTwoId { get; set; }
}
where PersonOne.name == PersonTwo.firstname && PersonOne.surname == PersonTwo.lastname but I have no idea how I can do that - because below code isn't efficient and is so slow:
List<PersonOne> personOneList = new List<PersonOne>();
List<PersonTwo> personTwoList = new List<PersonTwo>();
List<PersonOnePersonTwo> personOnePersonTwoList = new List<PersonOnePersonTwo>();
foreach (PersonOne personOne in personOneList)
{
foreach(PersonTwo personTwo in personTwoList.Where(x => x.firstname == personOne.name && x.lastname == personOne.surname).ToList())
{
personOnePersonTwoList.Add(new PersonOnePersonTwo
{
PersonOneId = personOne.id,
PersonTwoId = personTwo.id
});
}
};
Try this:
var result = personOneList.Join
(
personTwoList,
person1 => new { Key1 = person1.Name, Key2 = person1.Surname },
person2 => new { Key1 = person2.FirstName, Key2 = person2.LastName },
(person1, person2) => new PersonOnePersonTwo { PersonOneId = person1.Id, PersonTwoId = person2.Id }
).ToList();
I would go with:
var personOnePersonTwoList = new List<PersonOnePersonTwo>();
foreach (var personOne in personOneList)
{
personOnePersonTwoList = personTwoList.Where(x => x.firstname.Equals(personOne.name, StringComparison.OrdinalIgnoreCase) &&
x.lastname.Equals(personOne.surname, StringComparison.OrdinalIgnoreCase))
.Select(x => new PersonOnePersonTwo {PersonOneId = personOne.id, PersonTwoId = x.id}).ToList();
};
As a side note: it's more convinient to use Equals when comparing strings.
i have Contact query which contains Communication sub-query which contains CommunicationExtension sub-query
static class Program
{
public class Contact
{
public int ContactID { get; set; }
public List<Communication> Communications { get; set; }
public DateTime? DeletionDate { get; set; }
}
public class Communication
{
public int CommuncationID { get; set; }
public List<CommunicationExtension> CommunicationExtensions { get; set; }
public DateTime? DeletionDate { get; set; }
}
public class CommunicationExtension
{
public int CommunicationExtensionID { get; set; }
public int AreaCode { get; set; }
public DateTime? DeletionDate { get; set; }
}
static void Main(string[] args)
{
IQueryable<Contact> q = GenerateData();
IQueryable<Contact> result =
q.Where(c => c.DeletionDate == null &&
c.Communications.Where(co => co.DeletionDate == null &&
co.CommunicationExtensions.Where(ce => ce.DeletionDate == null));
}
private static IQueryable<Contact> GenerateData()
{
return new List<Contact>
{
new Contact
{
ContactID = 1,
DeletionDate = DateTime.Now,
Communications =
new List<Communication>
{
new Communication
{
CommuncationID = 1,
DeletionDate = DateTime.Now,
CommunicationExtensions =
new List<CommunicationExtension>
{
new CommunicationExtension
{
CommunicationExtensionID = 1,
AreaCode = 5,
DeletionDate = null
}
}
},
new Communication
{
CommuncationID = 2,
DeletionDate = null,
CommunicationExtensions =
new List<CommunicationExtension>
{
new CommunicationExtension
{
CommunicationExtensionID = 2,
AreaCode = 55,
DeletionDate = DateTime.Now
}
}
}
}
},
new Contact
{
ContactID = 2,
DeletionDate = null,
Communications =
new List<Communication>
{
new Communication
{
CommuncationID = 1,
DeletionDate = null,
CommunicationExtensions =
new List<CommunicationExtension>
{
new CommunicationExtension
{
CommunicationExtensionID = 3,
AreaCode = 54,
DeletionDate = null
}
}
},
new Communication
{
CommuncationID = 2,
DeletionDate = DateTime.Now,
CommunicationExtensions =
new List<CommunicationExtension>
{
new CommunicationExtension
{
CommunicationExtensionID = 4,
AreaCode = 5565,
DeletionDate = null
}
}
}
}
}
}.AsQueryable();
}
}
When i try to build it, i get the error:
Operator '&&' cannot be applied to operands of type 'bool' and 'System.Collections.Generic.IEnumerable'
on line:
IQueryable<Contact> result =
q.Where(c => c.DeletionDate == null &&
c.Communications.Where(co => co.DeletionDate == null &&
co.CommunicationExtensions.Where(ce => ce.DeletionDate == null)));
I need to filter all data that is not deleted (DeletionDate == null). In my scenario there is ~200 tables in database, each table contains nullable field DeletionDate
Here's the problem:
c.Communications.Where(co => co.DeletionDate == null &&
co.CommunicationExtensions.Where(ce => ce.DeletionDate == null)
Those two lines don't return a boolean, so your Where call doesn't know what to do with it. Are you wanting any Contact that has at least one non-deleted Communications and CommuincationExtensions? If so, then change the Where calls to Any and it should work. However, note that when actually dealing with your Contacts you'll still need to filter out any deleted Communications/CommunicationExtensions as the relationships will just get you the related records no matter what. In other words, contact.Communications will return all Communications related to that Contact, and comm.CommunicationExtensions will return all CommunicationExtensions, so you'll still need to filter out any deleted records whenever you deal with them.