I am working on a solution that uses the entity framework code first approach:
[XmlRoot(ElementName = "item")]
public class Item
{
[XmlElement("itemId")]
[Index("idx_item_id")]
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public long ItemId{ get; set; }
[XmlElement("otherId")]
[Index("idx_other_id")]
public long OtherId{ get; set; }
[XmlElement("randomStuff")]
public string RandomStuff{ get; set; }
}
And is directly mapped as:
public class DataContext : DbContext
{
public DataContext()
: base("name=DataContext")
{
Database.CommandTimeout = 180;
}
public DbSet<Item> Items{ get; set; }
So basically I have XMLs coming in and these are directly mapped with the model. A HTTP POST comes in, xml is deserialized using the model and then directly inserted to the database. Now I am no longer interested in a field RandomStuff, but I don't want to change the schema, I would simply start inserting NULLs there. Would it make sense to write something like:
private string _randomStuff;
[XmlElement("randomStuff")]
public string RandomStuff
{
get { return _randomStuff; }
set
{
_randomStuff = null;
}
}
Or is there a better way to achieve this?
The best thing of course is to bite the bullet and change the schema. But I know there can be many reasons not to do that (just yet).
A better option (then the null assignment in the setter) is to use a private setter:
public string RandomStuff { get; private set; }
EF can handle private setters and by doing this, EF will never think the property has changed (because it reads a different value than the one it was set with) and fire useless updates. And you will still be able to read old content.
If you don't want to display the content, even if it's still there, I'd replace the mapped property by a new dummy property (again with a private setter) and mark the current property as not mapped.
Related
I have an parent class and two child like these:
public class Parent {
public Guid Id { get; set; }
public string Name { get; set; }
}
public class FirstChild {
public string IdentityCode { get; set; }
}
public class OtherChild {
public string RegistrationCode { get; set; }
}
There is a question: Is it a good approach to store these two inherited classes in the same Index inside ElasticSearch?
I see there is a _type property that is added to my docs after they are stored in DB but it has always "doc" value.
I test this code to fill it but it seems it is not working this way.
await ElasticClient.IndexAsync<FirstChild>(child, m => m.Index(IndexName));
And Also, I found this question on SO for retrieving my entries from DB but it is outdated and the API is changed and no more accessible.
I want to know if it is a good approach to store sibling data in the same index how can I do this properly.
As of ES 6.0, it is not possible anymore to store multiple types inside the same index, i.e. the _type field you're referring to will always be either doc or _doc. In ES 8.0, the _type field will be removed altogether.
However, if it makes sense for your use case, you can still decide to store several types inside a single index using a custom type field that is present in your document.
You should strive to only store in the same index data that share the same (or very similar) mapping, which doesn't seem to be the case for Parent, FirstChild and SecondChild, but if you add a public string type property to your classes you can still do it.
I have written an attribute class which I later used for sorting properties.
[AttributeUsage(AttributeTargets.Property)]
class OrderAttribute : Attribute
{
internal OrderAttribute(int order)
{
Order = order;
}
public int Order { get; private set; }
}
I want this to be unique for class properties, e.g.
Valid scenario
[Order(1)]
public string Tier3 { get; set; }
[Order(2)]
public string Tier4 { get; set; }
Invalid Scenario since value "1" is repeated.
[Order(1)]
public string Tier3 { get; set; }
[Order(1)]
public string Tier4 { get; set; }
PS: Attribute values can be repeated for different class properties but not in same. How can I achieve this?
Although attribute values can be repeated, there's no easy way supported to make sure they are unique (they are run time only), you would need to check when actually sorting as Johnathan has already mentioned. There are ways around this, but is it worth it in the long run? A few options I can think of are:
Hook into the actual build process, create a build task that uses reflection to check and fail if needed.
Run a post-build (post build event) step that loads your dll and reflects on those attribute types.
Create a possible rule that will check for uniqueness.
There may be other ways, but these are the one's I could think of at the moment.
I'm going to create some tables with Entity Framework and the code-first approach. However some of my classes have complex properties like:
public class Car
{
public ComplexDate DateBought { get; set; }
}
where ComplexDate is:
public class ComplexDate
{
public int? Year { get; set; } // Notice the optional Year.
public string Month { get; set; }
public int Day { get; set; }
}
and can parse values like 27AUG or 27AUG15
Can I somehow configure my Car or ComplexDate so that I can serialize it into a string or deserialize back from a string? I'd like to have a column in the database called DateBought but in code I wish I could use the ComplexDate type for it and be able to parse the value stored in the database.#
IMPORTANT:
I have a few other complex properties that are not dates but are parsable that I'd like to store as strings as well and not in still more tables/column. It would overnomalize the database. I think I don't need it.
UPDATE:
Here's another example of what I mean:
public class Car
{
public CarColor Color { get; set; }
}
public class CarColor
{
private string _value;
// ...more code (ctr, parse etc.)
public override string ToString()
{
return _value;
}
}
Now I'd like to have a Car-table with a column named Color that would automatically (by some magic) turn into CarColor in code... Is there a way? Making the Color property (and others) a string breaks the whole design of my application because each an every property is a complex type because it has some logic for parsing, allowed values etc. I'd like it to be consistent (everything is complex type) instead of mixing string and classes and other types.
IMHO you probably want the EF property to be DateTime and just do the conversion in the UI. That way you can bind to a proper database date column and be able to do all the sorting and querying that would be impossible if use your approach.
You could store the date fields individually.
One for Year (nullable), one for Month, one for Day.
That way, you can still sort, group etc. from the database, and use the values in your class to combine and display as you wish.
I currently have the following Models in my EF Code First MVC project (edited for brevity):
public class Car
{
public int Id { get; set; }
public string Descrip { get; set; }
// Navigation Property.
public virtual CarColour CarColour { get; set; }
... + numerous other navigation properties.
}
public class CarColour
{
public int Id { get; set; }
public string ColourName { get; set; }
}
The CarColour table in the DB contains many rows.
In my project, I have about 10 of these sorts of tables, which are essentially lookup tables.
Rather than have 10 lookup tables (and 10 corresponding 'hard' types in code), I was tasked with implementing a more re-usable approach, instead of having loads of lookup tables, specific to Car (in this example), along the lines of having a couple of tables, one of which may hold the item types (colour, fuel-type etc.) and one which contains the various values for each of the types. The idea being that our model will be able to be re-used by many other projects - some of which will have potentially hundreds of different attributes, and as such, we won't want to create a new Class/Type in code and generate a new lookup table for each.
I am having difficulty in understanding the c# implementation of this sort of approach and hope someone may be able to give me an example of how this can be achieved in code, more specifically, how the above models would need to change, and what additional classes would be required to accomplish this?
your base entity must implement INotifyPropertyChanged and make it generic:
public virtual CarColour CarColour {
Get { return this.carColour; }
Set {
this.Carcolour; = value
OnPropertyChanged("CarColour");
}
}
For more info see :
patterns & practices: Prism in CodePlex.
http://compositewpf.codeplex.com/wikipage?title=Model%20View%20ViewModel%20(MVVM)
Greetings
Bassam
This is not necessarily specific to EF but I've been down this road and didn't really enjoy it.
I wanted to use a single table to represent 'generic' information and while I thought it was smart, it soon showed it's limitations. One of them being the complexity you need to introduce when writing queries to extract this data if you're performing more than just 'get colours for this car'.
I'd say, if your data is simple key/value and the value type is always going to be the same then go for it, it might even be worth having this a mere 'meta-data' for an object:
public class Car
{
public int Id { get; set; }
public string Descrip { get; set; }
public MetaData CarColours { get; set; }
}
public MetaData : Dictionary<int, string>
{
public MetaData(int group){}
}
Hypothetical table:
TableMetaData(int metaGroup, int metaId, string metaValue)
If you're hoping to store different types as your value and may need to perform joining on this data - avoid it and be a bit more specific.
I want to implement a simple attribute that is used to map Database Columns to Properties.
So what i have so far is something that attached like so:
[DataField("ID")]
public int ID { get; set; }
[DataField("Name")]
public String Name { get; set; }
[DataField("BirD8")]
public DateTime BirthDay { get; set; }
Is there a way that I can make the attribute "aware" of the field it is on, so that for the properties where the name is the same as the ColumnName I can just apply the attribute without the name parameter, or would I have to deal with that at the point where I reflect the properties. I want to end up doing just this:
[DataField]
public int ID { get; set; }
[DataField]
public String Name { get; set; }
[DataField("BirD8")]
public DateTime BirthDay { get; set; }
The attribute itself won't be aware of what it's applied to, but the code processing the attributes is likely to be running through PropertyInfo values etc and finding the attributes associated with them. That code can then use both the property and the attribute appropriately.
To make things simpler, you might want to write a method on the attribute to allow it to merge its information with the information from the property, so you'd call:
DataFieldAttribute dfa = propertyInfo.GetCustomAttributes(...); // As normal
dfa = dfa.MergeWith(propertyInfo);
Note that for the sake of sanity this should create a new instance of the attribute, rather than changing the existing one. Alternatively, you might want a whole separate class to represent "the information about a data field":
DataFieldAttribute dfa = propertyInfo.GetCustomAttributes(...); // As normal
DataFieldInfo info = dfa.MergeWith(propertyInfo);
That way you could also construct DataFieldInfo objects without any reference to attributes, which might be a nice conceptual separation - allowing you to easily load the config from an XML file or something similar if you wanted to.
If you don't mind using postsharp you can look Here, at a previous question I have asked which was close. I ended up using the compile time validate to do what I wanted, although there are other options, like CompileTimeInitalize.
public override void CompileTimeInitialize(object element)
{
PropertyInfo info = element as PropertyInfo;
//....
}