ASP NET Core reading complex configuration with array and JsonConverter - arrays

I have this appsettings.json
"TopLevel": [
{
"Name": "Name",
"TopChild": {
"File": {
"URL": "SomeUrl",
"Username": "Admin",
"Password": "123"
}
},
"TopChild2": [
{
"Name": "SimpleMapper",
"Mapper": {
"Param1": "",
"Param2": "",
"Param3": ""
}
},
{
"Name": "SimpleFileConverter",
"Converter": {
"ToWhat": "",
"Writer": ""
}
}
],
"TopChild3": {
"SomeProperty3": {
"WhatIsThis": "",
"SomeProp": "",
"Password": ""
}
}
},
{
"Name": "Name",
"TopChild": {
"DB": {
"ConnectionString": "String",
"Username": "Admin",
"Password": "123"
}
},
"TopChild2": [
{
"Name": "SomeConverter",
"Converter": {
"Param1": "",
"Param2": ""
}
},
{
"Name": "SimpleFileConverter",
"Mapper": {
"Param1": "",
"Param2": "",
"Param3": ""
}
}
],
"TopChild3": {
"SomePropety4": {
"SomeProp7": "",
"Password": ""
}
}
}
]
And this is the code I wrote for a model
public class TopLevelConfigRoot
{
[JsonProperty("TopLevel")]
public List<TestObject> TopLevel { get; set; }
}
public class TestObject
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("TopChild")]
[JsonConverter(typeof(TopChildConverter))]
public TopChildBase TopChild { get; set; }
[JsonProperty("TopChild2")]
[JsonConverter(typeof(TopChild2Converter))]
public List<TopChild2> TopChild2 { get; set; }
[JsonProperty("TopChild3")]
[JsonConverter(typeof(TopChild3Converter))]
public TopChild3Base TopChild3 { get; set; }
}
public abstract class TopChildBase { }
public abstract class TopChild3Base { }
public class File : TopChildBase
{
[JsonProperty("URL")]
public string URL { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class DB : TopChildBase
{
[JsonProperty("ConnectionString")]
public string ConnectionString { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public interface ITopChild2
{
public string Name { get; set; }
public ITopChild2Type ITopChild2Type { get; set; }
}
public class TopChild2 : ITopChild2
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("ITopChild2Type")]
public ITopChild2Type ITopChild2Type { get; set; }
}
public abstract class ITopChild2Type
{ }
public class Mapper : ITopChild2Type
{
[JsonProperty("Param1")]
public string Param1 { get; set; }
[JsonProperty("Param2")]
public string Param2 { get; set; }
[JsonProperty("Param3")]
public string Param3 { get; set; }
}
public class Converter : ITopChild2Type
{
[JsonProperty("Param1")]
public string Param1 { get; set; }
[JsonProperty("Param2")]
public string Param2 { get; set; }
}
public class SomeProperty3 : TopChild3Base
{
[JsonProperty("WhatIsThis")]
public string WhatIsThis { get; set; }
[JsonProperty("SomeProp")]
public string SomeProp { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class SomePropety4 : TopChild3Base
{
[JsonProperty("SomeProp7")]
public string SomeProp7 { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class TopChildConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChildBase);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo.ContainsKey(nameof(File)))
{
return jo[nameof(File)].ToObject<File>();
}
else if (jo.ContainsKey(nameof(DB)))
{
return jo[nameof(DB)].ToObject<DB>();
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class TopChild3Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChild3Base);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo.ContainsKey(nameof(SomeProperty3)))
{
return jo[nameof(SomeProperty3)].ToObject<SomeProperty3>();
}
else if (jo.ContainsKey(nameof(SomePropety4)))
{
return jo[nameof(SomePropety4)].ToObject<SomePropety4>();
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class TopChild2Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChild2);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray ja = JArray.Load(reader);
List<TopChild2> topChild2List = new List<TopChild2>();
foreach (var item in ja)
{
JObject jObject = (JObject)item;
TopChild2 TopChild2 = null;
string name = jObject[nameof(TopChild2.Name)].ToString();
if (jObject.ContainsKey(nameof(Mapper)))
{
var root = jObject[nameof(Mapper)];
Mapper mapper = new Mapper
{
Param1 = root[nameof(Mapper.Param1)].Value<string>(),
Param2 = root[nameof(Mapper.Param2)].Value<string>(),
Param3 = root[nameof(Mapper.Param3)].Value<string>()
};
TopChild2 = new TopChild2 { Name = name, ITopChild2Type = mapper };
}
else if (jObject.ContainsKey(nameof(Converter)))
{
var root = jObject[nameof(Converter)];
Converter converter = new Converter
{
Param1 = root[nameof(Converter.Param1)].Value<string>(),
Param2 = root[nameof(Converter.Param2)].Value<string>()
};
TopChild2 = new TopChild2 { Name = name, ITopChild2Type = converter };
}
topChild2List.Add(TopChild2);
}
return topChild2List;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
And now with that model I've tried using any known implementation of config inside of controller.
The only thing I came up is inserting IConfiguration via Dependency Injection and use _config = config;
And then selected it by
var section = _config.GetSection("TopLevel");
and then used it like this
var itemArray = section.AsEnumerable();
How can I then use this itemArray to convert this to either model, or a JsonString which i will then easily serialize it with Newtonsoft
var t = JsonConvert.DeserializeObject<TopLevelConfigRoot>(jsonString);
But I haven't find a way to map this itemArray to model I provided, nor I had success with writing recursive method to actually map it to JsonString.
Converter I wrote is
public string ConvertBackToJSonString(KeyValuePair<string, string>[] itemArray)
{
var root = new JObject();
var current = root;
foreach (var item in itemArray)
{
var parts = item.Key.Split(':');
var key = parts[parts.Length - 1];
var parent = current;
for (int i = 0; i < parts.Length - 1; i++)
{
var part = parts[i];
if (!current.ContainsKey(part))
current.Add(part, new JObject());
current = (JObject)current[part];
}
if (!string.IsNullOrEmpty(item.Value))
current.Add(key, new JValue(item.Value));
else
current.Add(key, new JObject());
current = parent;
}
return JsonConvert.SerializeObject(root, Formatting.Indented);
}
But that didn't work. How should this be approached to/done?

You could bind the section to a model directly with IConfigration.Bind() method
For example,in your case :
public class BindTarget
{
public string Name { get; set; }
public SomeChildClass1 TopChild { get; set; }
public List<SomeChildClass2> TopChild2 { get; set; }
public SomeChildClass3 TopChild3 { get; set; }
}
public class SomeChildClass1
{
public File File { get; set; }
public DB DB { get; set; }
}
public class SomeChildClass2
{
public string Name { get; set; }
public Mapper Mapper { get; set; }
public Converter Converter { get; set; }
}
public class SomeChildClass3
{
public SomeProperty3 SomeProperty3 { get; set; }
public SomePropety4 SomePropety4 { get; set; }
}
bind as below:
var targetobj = new List<BindTarget>();
Configuration.GetSection("TopLevel").Bind(targetobj);
var str = JsonConvert.SerializeObject(targetobj,new JsonSerializerSettings() { NullValueHandling=NullValueHandling.Ignore});
result:
The document related

Related

Always getting null value when send object with fromData other value from React

I have send a formData from react app with some value and image files and i also want to send a obj with same formData on .net core api
Here is my class
[Bind]
public class ServiceInfo
{
public int id { get; set; }
[NotMapped]
public IFormFile[] ImgFile { get; set; }
[NotMapped]
public IFormFile ImgFilen { get; set; }
//public int { get; set; }
public string title { get; set; }
public string serImg1 { get; set; }
public string serImg2 { get; set; }
public string serImg3 { get; set; }
public string serImg4 { get; set; }
public int serCategoryId { get; set; }
public SerCategory serCategory { get; set; }
public string time { get; set; }
public string location { get; set; }
public string serviceClose { get; set; }
public string serviceOpen { get; set; }
public int CompanyInfoId { get; set; }
public virtual CompanyInfo companyInfo { get; set; }
public string serviceDetails { get; set; }
public string offeredServices { get; set; }
public bool active { get; set; }
public bool status { get; set; }
public string extraServices { get; set; }
public string whyUs { get; set; }
}
.net core controler:
serCategory always getting null
[Route("PotService")]
[HttpPost]
public IActionResult Post([FromForm] ServiceInfo service)
{
//using (MemoryStream stream = new MemoryStream())
//{
// ImgFile.CopyToAsync(stream);
// service.Data = stream.ToArray();
//}
if (string.IsNullOrWhiteSpace(_rootPath.WebRootPath))
{
_rootPath.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "Images");
}
string uploadsFolder = Path.Combine(_rootPath.WebRootPath);
int index = 0;
foreach (var item in service.ImgFile)
{
index++;
if (item != null)
{
var uniqueFileName = service.title.ToString()+index.ToString()+ DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
switch (index)
{
case 1 :
service.serImg1 = uniqueFileName;
break;
case 2:
service.serImg2 = uniqueFileName;
break;
case 3:
service.serImg3 = uniqueFileName;
break;
case 4:
service.serImg4 = uniqueFileName;
break;
}
}
}
//bool result = _serManager.AddService(service);
foreach (var item in service.ImgFile)
{
if (item != null)
{
var uniqueFileName = service.title.ToString() + index.ToString() + DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
item.CopyTo(fileStream);
}
}
}
return Ok(true);
}
And react code :
const formData = new FormData();
formData.append("id", 0);
formData.append("CompanyInfoId", activeComId);
formData.append("title", data.title);
formData.append("time", "");
formData.append("location", data.location.value);
formData.append("serviceClose", data.serviceClose.value);
formData.append("serviceOpen", data.serviceOpen);
formData.append("serviceDetails", data.serviceDetails);
formData.append("serCategoryId", data.serType.id);
formData.append("serCategory", data.serType);
formData.append("offeredServices", data.offeredServices);
formData.append("active", false);
formData.append("status", false);
formData.append("extraServices", data.extraServices);
formData.append("whyUs", data.whyUs);
formData.append("ImgFile", data.serImg1);
formData.append("ImgFile", data.serImg2);
formData.append("ImgFile", data.serImg3);
formData.append("ImgFile", data.serImg4);
for (const [key, value] of formData.entries()) {
console.log(key, value);
}
console.log(data.serType);
const res = await fetch(serPost, {
method: "POST",
body: formData,
});

How insert new array into existing embedded array in C#?

I have a little bit problem with an data update in mongoDB. I have an array embedded in an other array who is embedded in a document (yaaaaay ^^). So my collection is like that :
{
"_id" : ObjectId("5965e0b4f1042c4c3f1d8edc"),
"Builder" : "Google",
"Family" : "Car",
"ProductName" : "ABCD_80A_PU170017",
"ProductNumber" : "N 1",
"Test" : [
{
"Num_Test" : "PU170017",
"Date_Start" : ISODate("2017-07-12T00:00:00.000Z"),
"Bench": [
{
"Room": 1,
"Num" : 1,
"Designation" : "AC1; AC3",
"IP" : "123.456.78.9",
"Capacity" : 12,
}
],
"User" : [
{
"Number" : "EBBW396",
"Password" : "titi",
"Name" : "NDJO",
"Surname" : "Charles",
"Tel" : "06XXXXXX",
"isAdmin" : true
}
]
}
]
}
And i want to insert a new array embedded in "Test".
So i found my happiness here : https://docs.mongodb.com/getting-started/csharp/update/ AND How to use C# to insert document into existing embedded documents?
And i have write this code :
static void Main(string[] args)
{
IMongoClient client = new MongoClient("mongodb://10.194.157.199:27017");
IMongoDatabase database = client.GetDatabase("PINEA");
IMongoCollection<Product> collection = database.GetCollection<Product>("Product");
var filter = Builders<Product>.Filter.Eq("Test.Num_Test", "PU170017");
var meter = new Meter();
meter.Value= 12;
meter.Date = DateTime.Now;
var meterList = new List<Meter>();
meterList.Add(meter);
var update = Builders<Product>.Update.Push("Result", new Result
{
MeterList = meterList
});
var result = collection.UpdateOne(filter, update);
}
But nothing happens, nothing has added or modified. I miss something important but i don't understand what is it.
Finally, here are my classes:
class Result
{
public List<Meter> MeterList { get; set; }
public List<Problem> Problem { get; set; }
}
class Meter
{
public int? Value { get; set; }
public DateTime? Date { get; set; }
}
class Test
{
public string Num_Test { get; set; }
public DateTime? Date_Start { get; set; }
public List<Bench> Bench { get; set; }
public List<User> User { get; set; }
public List<Result> Result { get; set; }
}
class Product
{
public string Builder { get; set; }
public string Fammily { get; set; }
public string ProductName { get; set; }
public string ProductNumber { get; set; }
public List<Test> Test { get; set; }
}
To explain the context, I need to update the array "result" regularly and maintain data arborescence like that. After the end of the test, data aren't modify anymore.
PS : I'm still a student but I work part time
Thanks

How to convert Directory Folders and Files to json string

I am working on Windows Form and I want to convert Directory Folders and Files to Json string like below,I am using newton json and have a json string like below with multiple Folders and Files , dynamic.
{
"folder": {
"name": "abc",
"folders": {
"folder": {
"name": "child abc",
"folders": {
"folder": {
"name": "child abcd"
}
},
"assets": {}
}
},
"assets": {
"asset": {
"folder_id": 14,
"uploaded_file": {
"content_type": "image/png",
"filename": "settings.png",
"file_data": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABsVJREFUeNrEV29"
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
The Classes i am using are below mentioned, how can i get a json string with multiple Folders and Files.??
Help me
public class Folders2
{
}
public class Assets
{
}
public class Folder2
{
public string name { get; set; }
public Folders2 folders { get; set; }
public Assets assets { get; set; }
}
public class Folders
{
public Folder2 folder { get; set; }
}
public class UploadedFile
{
public string content_type { get; set; }
public string filename { get; set; }
public string file_data { get; set; }
}
public class Asset
{
public int folder_id { get; set; }
public UploadedFile uploaded_file { get; set; }
}
public class Assets2
{
public Asset asset { get; set; }
}
public class Folder
{
public string name { get; set; }
public Folders folders { get; set; }
public Assets2 assets { get; set; }
}
public class RootObject
{
public Folder folder { get; set; }
}
////////////////////////////////////////////////////////////////////////////
I tried working on this getting Directories and Files in a List,
Can anyone tell me how to parse this like above json string
List<string> li = new List<string>();
li.Add(path);
foreach (string files in Directory.EnumerateFiles(path, "*.*", System.IO.SearchOption.TopDirectoryOnly))
{
bool exists2 = li.Exists(element => element.StartsWith(files));
if (exists2 == false)
{
li.Add(files);
}
}
foreach (string Folder in Directory.EnumerateDirectories(path, "*.*", System.IO.SearchOption.AllDirectories))
{
li.Add(Folder);
foreach (string file in Directory.EnumerateFiles(Folder, "*.*", System.IO.SearchOption.AllDirectories))
{
bool exists = li.Exists(element => element.StartsWith(file));
if (exists==false)
{
li.Add(file);
}
}
}
Well I can see two ways to create your JSON-string from the object.
) You manually create the json-string with iterateing through the object and its properties.
) Use for IE. JSON.NET (http://www.newtonsoft.com/json/help/html/Introduction.htm) Serialize your object to json.
But I think you also should rethink the design of the classes, but thats an other thing.
With help and effort from Fredrik M , I have achieved my desired task
public class FolderRoot1
{
public FolderSJ folder { get; set; }
}
public class FolderSJ
{
public FolderSJ()
{
assets =new List<AssetRoot> { };
folders = new List<FolderRoot1> { };
}
public string parent_id { get; set; }
public string name { get; set; }
public List<AssetRoot> assets { get; set; }
public List<FolderRoot1> folders { get; set; }
}
public class AssetSJ
{
public string filename { get; set; }
public string content_type { get; set; }
public string file_data { get; set; }
}
public class AssetRoot
{
public UploadedFileContent asset { get; set; }
}
public class UploadedFileContent
{
public AssetSJ uploaded_file { get; set; }
}

Sending object to sql server in ASP.NET MVC4 Architecture

I am getting an exception on db.CrimeReports.Add(i);
"An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code "
[HttpPost]
public void Test(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
using (UsersContext db = new UsersContext())
{
//db.LoginData.Add(new LoginData { UserId = 4, Username = "maria", Password ="rahat"});
byte[] image = new byte[file.ContentLength];
file.InputStream.Read(image, 0, image.Length);
var i = new CrimeReport { ImageName = "murder", ImageContent = image, Active =false};
db.CrimeReports.Add(i);
db.SaveChanges();
}
}
else
{
ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
}
}
Here is my CrimeReport class
[Table("CrimeReport")]
public class CrimeReport
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int ImageId { get; set; }
public string ImageName { get; set; }
public byte[] ImageContent { get; set; }
public string Createdby { get; set; }
public System.DateTime CreatedDt { get; set; }
string Updatedby { get; set; }
public Nullable<System.DateTime> UpdatedDt { get; set; }
public bool Active { get; set; }
public virtual ReportDescription ReportDescription { get; set; }
}

How to make dataannotations outside the entities

I'm using Wpf and EntityFrameWork in my project. I wanted to use DataAnnotations since it is a better way to validate the data. I managed to make it in my entity files. For example one of my entities include these:
public partial class Employee : INotifyPropertyChanged, IDataErrorInfo
{
public Employee()
{
this.Address = new HashSet<Address>();
this.Certificate = new HashSet<Certificate>();
this.ContactInformation = new HashSet<ContactInformation>();
this.Course = new HashSet<Course>();
this.Education = new HashSet<Education>();
this.EmployeeTeam = new HashSet<EmployeeTeam>();
this.Evaluation = new HashSet<Evaluation>();
this.ExamInformation = new HashSet<ExamInformation>();
this.JobTitle = new HashSet<JobTitle>();
this.MilitaryService = new HashSet<MilitaryService>();
this.Relationship = new HashSet<Relationship>();
this.WorkExperience = new HashSet<WorkExperience>();
}
public int Id { get; set; }
private string _CitizenId;
[Required(ErrorMessage = "CitizenId is required!")]
[RegularExpression(#"^\d+$", ErrorMessage = "Only numbers allowed")]
public string CitizenId
{
get
{
return _CitizenId;
}
set
{
_CitizenId = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("CitizenId"));
}
}
}
private int _RegNumber;
[Required (ErrorMessage = "Registration Number is required!")]
[RegularExpression(#"^\d+$", ErrorMessage = "Only numbers allowed")]
public int RegNumber
{
get
{
return _RegNumber;
}
set
{
_RegNumber = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("RegNumber"));
}
}
}
public Nullable<short> ResourceTypeId { get; set; }
public Nullable<short> EmployeeRoleId { get; set; }
private string _FirstName;
[Required(ErrorMessage="Name is required!")]
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage="Numeric expressions are not allowed!")]
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
}
}
}
private string _MiddleName;
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "Numeric expressions are not allowed!")]
public string MiddleName
{
get
{
return _MiddleName;
}
set
{
_MiddleName = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("MiddleName"));
}
}
}
private string _Surname;
[Required(ErrorMessage= "Surname is required!")]
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "Numeric expressions are not allowed!")]
public string Surname {
get
{
return _Surname;
}
set
{
_Surname = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Surname"));
}
}
}
private int _CustomerNo;
[Required(ErrorMessage = "Customer Number is required!")]
[RegularExpression(#"^\d+$", ErrorMessage = "Only numbers allowed")]
public int CustomerNo
{
get
{
return _CustomerNo;
}
set
{
_CustomerNo = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("CustomerNo"));
}
}
}
public System.DateTime BirthDate { get; set; }
private string _BirthPlace;
[Required(ErrorMessage="Birh Place is required!")]
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "Numeric expressions are not allowed!")]
public string BirthPlace
{
get
{
return _BirthPlace;
}
set
{
_BirthPlace = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("BirthPlace"));
}
}
}
public string Gender { get; set; }
public string MaritalStatus { get; set; }
public System.DateTime WorkBeginDate { get; set; }
//indicates that whether the start date is bigger than the end date which is a validation problem
// [CustomValidationsForDate("WorkBeginDate", ErrorMessage="Starting date cannot be bigger than the ending date")]
public Nullable<System.DateTime> WorkEndDate { get; set; }
private string _LogonName;
[Required(ErrorMessage = "Logon Name is required!")]
public string LogonName
{
get
{
return _LogonName;
}
set
{
_LogonName = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("LogonName"));
}
}
}
private int _DistanceToWork;
[RegularExpression(#"^\d+$", ErrorMessage = "Only numbers allowed")]
[Required(ErrorMessage="This field is required!")]
public int DistanceToWork
{
get
{
return _DistanceToWork;
}
set
{
_DistanceToWork = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("DistanceToWork"));
}
}
}
public Nullable<bool> HasInternet { get; set; }
public Nullable<bool> HasRemoteConnection { get; set; }
public int MilitaryStatus { get; set; }
public Nullable<int> DrivingLicense { get; set; }
public bool IsSmoker { get; set; }
public bool IsActive
{ get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public string LeavingReason { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> EndDate { get; set; }
public virtual ICollection<Address> Address { get; set; }
public virtual ICollection<Certificate> Certificate { get; set; }
public virtual ICollection<ContactInformation> ContactInformation { get; set; }
public virtual ICollection<Course> Course { get; set; }
public virtual ICollection<Education> Education { get; set; }
public virtual ICollection<EmployeeTeam> EmployeeTeam { get; set; }
public virtual ICollection<Evaluation> Evaluation { get; set; }
public virtual ICollection<ExamInformation> ExamInformation { get; set; }
public virtual ICollection<JobTitle> JobTitle { get; set; }
public virtual ICollection<MilitaryService> MilitaryService { get; set; }
public virtual ICollection<Relationship> Relationship { get; set; }
public virtual ICollection<WorkExperience> WorkExperience { get; set; }
//Following methos have been used in order to apply DataAnnotations
public event PropertyChangedEventHandler PropertyChanged;
public string Error { get { return String.Empty; } }
public string this[string property]
{
get { return ValidateProperty(this, property); }
}
public static string ValidateProperty(object instance, string propertyName)
{
PropertyInfo property = instance.GetType().GetProperty(propertyName);
object value = property.GetValue(instance, null);
List<string> errors = (from v in property.GetCustomAttributes(true).OfType<ValidationAttribute>()
where !v.IsValid(value)
select v.ErrorMessage).ToList();
return (errors.Count > 0) ? String.Join("\r\n", errors) : null;
}
}
}
So like I said I'm applying dataannotations inside the entities but what I want is doing that outside because whenever a change occurs in my database, all the entities will be refreshed so what I have here is not a dynamic structure.
So could you please help?
Thanks in advance.
Best regards.
Ege
You should create a model (view model) class and map from your entities (domain models) to the view model. AutoMapper can help speed this up. You then put your annotations on your view models and use these in your views.
This means that if your entity model changes you just need to update the mapping. It also means that you can create multiple different models for the same entity so your validation doesn't have to be the same for each view that uses it.

Resources