Dynamic property to a C# object - c#

I am thinking designing a field in db that stores the Serialized Object. When I call that property in entity, that returns String property which is obvious. I am looking for a way to attach a property dynamically and assign the deserialized object to the Class instance. Can any one suggest the best possible way?
DB Structure
Users Table
UserId ..... ..... ..... UserNotes (nvarchar)
Class Structure
[Serializable]
[XmlRoot("Notes")]
public class GenericNotes {
public DateTime Date {
get;
set;
}
public String CommentBy {
get;
set;
}
public string Type {
get;
set;
}
public string Comment {
get;
set;
}
}
public class Users {
public UserId int {
get;
set;
}
public string UserNotes {
get;
set;
}
// I dont have the following definition in the class because its coming from entity framework.
//But I want the following property attached to the class on runtime.
//I will take care of of deserializing using extension methods or some sort methods.
public string List < GenericNotes > NotesCollection {
get;
set;
}
}

Instead of property you can have extension method to do this
public static class UserExtension
{
public static List<GenericNotes> GetNotes(this Users users)
{
//return your deserialized GenericNotes from string
}
}
Then you can use this anywhere like
List<GenericNotes> notes = users.GetNotes();

Related

Using Entity Framework Code-First, can I make my class generic and derive a store-able string field from the type?

My use-case:
I'd like to store a representation of a file tree in my local (SQLite) database using EF.
My model will be a simplified copy a much larger model on a remote SQL database (also in EF)
I'd like to use one, generic entity that self-refers to create a tree structure, and derives its 'type' field from one of the original entity types (FiletypeA, FiletypeB, Folder etc.. using the interface IFileSynchronisable)
I figured the best way was to make the class generic, and deriving a string field from the type using nameof(T) and Type.GetType("FiletypeA"), but I've got stuck trying to instantiate the class when building the model:
public class FileSyncObject<T> where T : class, IFileSynchronisable
{
[Key]
public Guid Id { get; set; }
public long ObjectId { get; set; }
//Can I derive T from some 'ObjectType' field in the record?
public string ObjectType { get { return nameof(T); } }
public long ProjectId { get; set; }
public string AmazonS3Path { get; set; }
public bool IsActive { get; set; }
public string Version { get; set; }
public Guid LocalParentId { get; set; }
public FileSyncObject<T> LocalParent { get; set; }
public virtual ICollection<FileSyncObject<T>> LocalChildren { get; set; }
}
What's the best approach? Is this even possible?

Passing values from concretized instance of an base class to another base class instance

I am currently working on making viewmodels capable of parsing data extracted from database to the UI and vice versa, and to do so I do a lot of manual mapping between my two viewmodels.
Currently I try to pass some values that determines an attribute, but since each attributetype requires specifying a lot specific parameter, and 90% of the variables will be redundant in all cases since attributes only have one type..
Thus i have create a placeholder base class, which just contains an Id, that each atttribute have,
and each of the specific attribute type parameter will then use this placeholder as base class..
example:
public class BooleanViewSpecification : AttributeTypeSpecification
{
public string TrueOptionText { get; set; }
public string FalseOptionText { get; set; }
}
public class DateTimeTypeViewSpecification : AttributeTypeSpecification
{
public DateTime EarliestDataTime { get; set; }
public DateTime LatestDataTime { get; set; }
}
and my Attribute class is just an
public class AttributeView
{
public DataType Type { get; set; }
public AttributeTypeSpecification AttributeTypeViewSpecification { get; set; }
}
And the same Goes for my DB view model
public class BooleanSpecification : AttributeTypeSpecification
{
public string TrueOptionText { get; set; }
public string FalseOptionText { get; set; }
}
public class DateTimeTypeSpecification : AttributeTypeSpecification
{
public DateTime EarliestDataTime { get; set; }
public DateTime LatestDataTime { get; set; }
}
and my Attribute class is just an
public class Attribute
{
public DataType Type { get; set; }
public AttributeTypeSpecification AttributeTypeSpecification { get; set; }
}
Problem is then mapping from one class to another class
public static IEnumerable<AttributeView> MapToViewModel(this IEnumerable<Attribute> attributes)
{
return attributes.Select(z => new AttributeView()
{
Type = z.Type,
AttributeTypeViewSpecification = z.AttributeTypeSpecification
});
}
Which does not seem to work?
I use entity framework and migrate using Code-First what I receive is the Id of the location, and not the actual values?
I cant seem to understand why I cant be given the values - if it during the mapping does have the value?
So why cant they be mapped over?
I retrieve the value
Context.Include(Attribute).ThenInclude(AttributeTypeSpecification)
The only thing I receive is the actual Id rather than the specified entries?

How can I automap an object with a JSON property to an object without a JSON property?

What is a good way is to automap an object with some properties, one of which is a JSON string, to another object where that JSON string would be represented by properties instead of JSON.
See the source and destination classes below for an example:
CustomJson will look something like this for this example but could be different for other AlertTypes: { "AlertPrice": 500.0 }
//This is the database table representation (source)
public class Alert
{
public int Id { get; set; }
public int UserId { get; set; }
public string AlertType { get; set; }
public string CustomJson { get; set; }
}
//This is the business logic model (destination)
public class UserAlert
{
public int Id { get; set; }
public int UserId { get; set; }
public string AlertType { get; set; }
//This comes from the CustomJson string in the DB
//A different AlertType may need to map to a different object with different properties
public decimal AlertPrice { get; set; }
}
Will a ValueResolver allow me to do this or will it only be able to map part of the object? If not, perhaps I should just have a Custom property which contain the custom info instead of trying to meld it into the top-level object.
CreateMap<sourceobject, destobject>()
.AfterMap((src, dest) =>
{
dest.AlertPrice = JsonConvert.DeserializeObject<T>(json).AlertPrice;
});
CreateMap<sourceobject, destobject().AfterMap((src, dest) =>
{
dest.AlertPrice = decimal.Parse(src.AlertPrice, CultureInfo.InvariantCulture);
});
Please use above code you have use Explicity Mapping

Is there a way to ignore class properties without using annotations

Following is the api call that return the Agent object
[Route("GetAgentById")]
public Agent GetAgentById(int id)
{
//Restrict Class fields
return new Agent(id);
}
Agent class have a lot of fields (Let say 100 fields)
public class Agent
{
public int AgentId { get; set; }
public string AgentName { get; set; }
public bool IsAssigned { get; set; }
public bool IsLoggedIn { get; set; }
......
......
public Agent() { }
}
Is there a way to ignore class properties without using annotations. I just want to return some of the fields of agent object before returning the agent object from api call. Is there any way to doing this
Return anonymous object with just required properties, like:
return new { agent.AgentId, agent.AgentName }
or use DTOs (which would be architecturally more correct, specially if you're building complex solution), in this example with Automapper:
return Mapper.Map<AgentDTO>(agent);
But if you really want to use "opt-out" approach and serialize just small subset of your object, and if you're using JSON.NET, you can mark just properties which needs to be serialized:
[DataContract]
public class Agent
{
// included in JSON
[DataMember]
public int AgentId { get; set; }
[DataMember]
public string AgentName { get; set; }
// ignored
public bool IsAssigned { get; set; }
public bool IsLoggedIn { get; set; }
}

C# Table Row to a Dynamic Class

I'm working on application in which the user defines classes using dedicated editor. The result of this step is db table which holds a class name and list of properties attached to it by the user.
The classes can only hold only primitive types, but struct, as parameters.
The next step is to load the table rows as dynamic objects to another application.
Beside using reflection, is there another way to convert table row to POCO?
These are the models:
[Description("represents the base model")]
public class
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Comment { get; set; }
}
public class ParameterModel : BaseModel
{
public string Type { get; set; }
public string DefaultValue { get; set; }
}
[Description("Represents dynamic activity")]
public class ActivityModel : BaseModel
{
public List<ParameterModel> Parameters { get; set; }
}
Thank you very much.

Categories

Resources