EntityFramework 4.1 Code First incorrectly names complex type column names - entity-framework-4.1

Say I have a table called Users, which contains your typical information: Id, Name, Street, City--much like in the example here:
http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx.
Among other things, this article states:
"Code First has a concept of Complex Type Discovery that works based on a set of Conventions. The convention is that if Code First discovers a class where a primary key cannot be inferred, and no primary key is registered through Data Annotations or the fluent API, then the type will be automatically registered as a complex type. Complex type detection also requires that the type does not have properties that reference entity types (i.e. all the properties must be scalar types) and is not referenced from a collection property on another type." My Address class meets these criteria: it's made up of strings and isn't used anywhere else.
In the app, though (I'm not sure if this makes any difference), we're calling the Users something else--say, Techs. I want to break out User's address columns into an Address so each Tech can have its own Address. According to the article above, EF should infer this and take care of the complex type automatically. What I'm getting,though, when the context attempts to give me a Tech, is the following exception:
System.Data.EntityCommandExecutionException: An error occurred while executing t
he command definition. See the inner exception for details. ---> System.Data.Sql
Client.SqlException: Invalid column name 'Address_Street'.
Invalid column name 'Address_City'.
Invalid column name 'Address_State'.
Invalid column name 'Address_Zip'.
It looks like it's trying to make sense of the Tech.Address property, but is giving each of its sub-properties the wrong name (e.g., "Address_City" instead of "City").
Any ideas on how I can rectify this?

That is correct behavior. Default convention always prefixes properties mapped to complex type with type name. If you want to use different column names you must map them either through data annotations:
public class Address
{
[Column("City")]
public string City { get; set; }
...
}
or through fluent API:
modelBuilder.ComplexType<Address>().Property(a => a.City).HasColumnName("City");

Related

What is the difference between findBy with underscore and findBy without it?

Example: What is the difference between :
List<UserCompany> findByCompany_IdAndCompany_IsActivated(params)
and
List<UserCompany> findByCompanyIdAndCompanyIsActivated(params)
There is no difference if your model is unambiguous with respect to field names.
List<UserCompany> findByCompanyIdAndCompanyIsActivated(params) -
this first thinks that companyId and companyIsActivated are properties within UserCompany and tries to find them if fails
it then thinks that UserCompany has a field Company - which is another class and Company has field - Id and IsActivated and tries to find them
Where as the below thing
List<UserCompany> findByCompany_IdAndCompany_IsActivated(params)
assumes directly that UserCompany has a field Company - which is another class and Company has field - Id and IsActivated and tries to find them
From the spring documentation
Property expressions :---
Property expressions can refer only to a direct
property of the managed entity, as shown in the preceding example. At
query creation time you already make sure that the parsed property is
a property of the managed domain class. However, you can also define
constraints by traversing nested properties. Assume Persons have
Addresses with ZipCodes. In that case a method name of
List findByAddressZipCode(ZipCode zipCode); creates the
property traversal x.address.zipCode. The resolution algorithm starts
with interpreting the entire part (AddressZipCode) as the property and
checks the domain class for a property with that name (uncapitalized).
If the algorithm succeeds it uses that property. If not, the algorithm
splits up the source at the camel case parts from the right side into
a head and a tail and tries to find the corresponding property, in our
example, AddressZip and Code. If the algorithm finds a property with
that head it takes the tail and continue building the tree down from
there, splitting the tail up in the way just described. If the first
split does not match, the algorithm move the split point to the left
(Address, ZipCode) and continues.
Although this should work for most cases, it is possible for the
algorithm to select the wrong property. Suppose the Person class has
an addressZip property as well. The algorithm would match in the first
split round already and essentially choose the wrong property and
finally fail (as the type of addressZip probably has no code
property). To resolve this ambiguity you can use _ inside your method
name to manually define traversal points. So our method name would end
up like so:
List findByAddress_ZipCode(ZipCode zipCode);
Underscore is reserved character which allows you to point the right object to construct jpa query. It's used only with nested objects. For example if you would like to query by ZipCode inside Address inside you Company object.
More information can be found here

Model object properties identification

We are using SQLite property database to get information about object's properties. The problem we are facing with is property identification. For each property we have:
id: looks like it is just an autoincremental id and it can be used to
identify property between two versions of the same model
name: for .rvt models it is mostly unique, but there are some duplications
sometimes (for example the same property with different flags,
readonly and not); for .ifc files it is not unique at all
category + displayName: the problem with this
fields is that after using design automation API (to change and
re-save model) category/displayName can be translated into English
(but initially they can be, for example, in German)
Now we are using the combination of 'name + category + displayName' to identify the property, but it is not the solution, because this combination still is not unique in some rare cases (it is data lost for us) and it doesn't solve the problem with property names translation using Design Automation API.
Any ideas how to identify properties will be helpful! Thanks
For a given element, the externalId should be unique within that model (at the model level, the urn is unique). There is no unique identification for properties.
I'm interested in understand this workflow better, are you able to have a quick talk? Please use this link to book a time.

Problem Naming an Interface

I have an interface named PropertyFilter which used to take a Propertyand decide if accepts it or not. And the world was good.
But now the interface changed, so that implementations may choose to add additional Propertys. For example a Customer property might get expanded into Name and Address properties.
I think it is obvious this is not a Filter anymore, but how would you call such a thing?
To clarify: the so called filter is pretty much a method with the signature
Property -> List<Property>
With an empty List denoting not accepting the Property, a List with exactly the input Property denoting accepting the property and a List with new Properties (possibly including the original one) denoting an expansion.
PropertyChecker
PropertyValidator
PropertyDistillator
PropertyAccreditor
...
Do you already have a name for the method you mention ? It might help us find a proper name for the interface as well.
I'm not really sure what your new function does. If it still returns a boolean, then another name for a function which returns a boolean value is a "predicate".
If it takes a Customer and decomposes it (perhaps you have one function which takes a Customer and returns a Name, and another which returns an Address), then I might call them "accessors". This term is often used to describe a member function of an object, but I think it could apply here, too.
If Customer has a Name and and Address, the it is no longer a property, but an entity.
The Customer property could be a reference to a Customer entity, in which case the semantic convention for your interface still apply.
I would add a method named validate to Property with the signature:
PropertyFilter -> Bool
The default implementation of validate simply passes this (the Property) to the filter and returns the result:
def validate (filter: PropertyFilter) = filter (this)
As a compound property, Customer overrides validate, implementing it in terms of its composite properties:
override def validate (filter: PropertyFilter) = name.validate (filter) && address.validate (filter)
This way, each Property can describe how to apply any given PropertyFilter to itself. I think you should avoid the List expansion approach.

Linq to Sql inheritance mapping to multiple tables

I am having trouble with inheritance mapping in Linq to Sql. I am using MSDN as a reference and as a basis it sounds good. However the example it gives is a single table inheritance mapping. However, I am trying to do multiple table inheritance to save on table space. Is this possible? So far I have:
[Table(Name="writing_objs")]
[InheritanceMapping(Code="T",Type=typeof(ObjectTypeA), IsDefault=true)] // Only default because a default is required
[InheritanceMapping(Code="N",Type=typeof(ObjectTypeb))]
public abstract class WritingObject
{
/* ... */
[Column(Name="obj_tp", IsDiscriminator=true)]
[StringLength(1)]
public string ObjectType { get; set; }
}
I then have the different object types defined like so:
[Table(Name="obj_type_a")]
public class ObjectTypeA: WritingObject
{
/* Object Type A fields */
}
The issue seems to be that I am defining a table attribute in the 2nd type, as I get the following exception:
The inheritance subtype 'ObjectTypeA' is also declared as a root type.
Is it possible to keep these fields in separate tables with Linq to Sql or am I going to have to consolidate them all into a single table? Is it necessarily bad to have some extra fields in one table as long as there aren't too many (some object types might even be able to share some fields)?
Linq to SQL does not support multiple-table inheritance using a discriminator, even though that is the best design in many cases (it's the most normalized).
You'll have to implement it using associations instead. If you use a mapping layer that converts it to an inheritance-based domain model, it will be easier to manage at higher layers.
Well I know this problem has already been resolved, but as I just encountered the same issue, I'd like to share what I did :
Just remove the [Table] attribute from your inherited classes. And it's quite logical, because we define in the generic classes a way to store all subtypes (with the discriminatory attrbute).
Maybe this will help someone in the future.

applying separation of concerns

I wonder if you think that there is a need to refactor this class.( regarding separation of concern)
publi class CSVLIstMapping<T>
{
void ReadMappingFromAttirbutes();
void GetDataFromList();
}
ReadMappingFromAttributes - Reads the mapping from the type T and stores it in the class. Has a name of the list to use and a number of csvMappingColumns which contains the name of the property to set the value in and the name of csvcolumns.
GetObjectsFromList - uses a CVSListreader ( which is passed in via the constructor) to get the data from all row's as KeyValuePair ( Key = csvcolumnName , value = actually value) and after that it uses the mappinginformation( listname and csvMappingColumns ) to set the data in the object.
I cant decide if this class has 2 concerns or one. First I felt that it had two and started to refactor out the conversion from rows to object to another object. But after this it felt awkward to use the functionality, as I first had to create a mappingretriver, and after that I had to retrive the rows and pass it in together with the mapping to the "mapper" to convert the objects from the rows
/w
Sounds like two concerns to me: parsing and mapping/binding. I'd separate them. CSV parsing should be a well-defined problem. And you should care about more than mere mapping. What about validation? If you parse a date string, don't you want to make sure that it's valid before you bind it to an object attribute? I think you should.
Rule of thumb: if it's awkward, it's wrong.
I have to say I'm finding it hard to understand what you've written there, but I think it's likely that you need to refactor the class: the names seem unclear, any method called GetFoo() should really not be returning void, and it may be possible that the whole ReadMappingFromAttribute should just be constructor logic.