Entity Framework 4.0 mapping issues - c#

I'm getting the following error when trying to run a solution using Entity Framework 4.0 and am wondering how to change the mapping settings to correct it:
Problem in mapping fragments starting at line 588: Must specify mapping for all key properties (UserDatas.Id) of the EntitySet UserDatas
To give some background - I originally created the tables shown below with Modified/Created Date/By and Id columns in each of them, but then decided to pull them out into the abstract UserData and then use inheritance instead. Since I changed this it's all gone to pot!
Does anyone have any pointers as to where I'm going wrong? I've been using the design view show below (the GUI) and it feels like I've hit a brick wall.
My db.edmx design view looks like this, and clicking on the error takes me to the Variables table shown below, but the error is repeated for all the other tables that inherit this Id (please ignore all the links to other tables - I didn't want to post the whole big db schematic):
Many thanks.

Sounds like you are mis-using OO inheritance here. Just because objects share items with the same property names doesn't mean that they Inherit from the base. For example, ask yourself in your modle if Tag IS A UserData? I suspect you could phrase this better that Tag HAS A UserData which points to containment rather than inheritance. I would recommend setting up a common IUserData interface where each object implements the interface distinctly. In that case, your mapping then would move the properties for the UserData interface back into the underlying classes (as they were configured originally). While you may be able to get your mapping to work with the inheritance model, your queries will get significantly complex both from a LINQ and TSQL perspective.

Related

How to implement LinkedList in Entity Framework Core

I want to persist a linked list of objects using in my ASP.Net Core application. For simplicity, I'll use blog and comments; although the real context is much more complex.
I scaffolded two tables, and changed ICollection<Comment> to LinkedList<Comment>. However, if I create an initial migration and apply to an empty database, I don't get anything "linked" in the database (no next or previous). Also, if I seed the data, and then do something like this:
var comments = _context.blogs.First().Comments
I get null. If I leave public virtual ICollection<Comment> Comments, I get the IEnumerable just fine.
I tried to use LinkedList<LinkedListNode<Comment>> instead, and it works nice unless I try to create a migration. Getting an error
No suitable constructor found for entity type 'LinkedListNode'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'value' in 'LinkedListNode(Comment value)'; cannot bind 'list', 'value' in 'LinkedListNode(LinkedList list, Comment value)'.
I couldn't find any guidance how to implement LinkedList in C#/.NET Core (obviously, I can do it manually, having next and prev fields - but I would very much prefer to use framework capabilities, if possible!)
I don't know much about MS SQL server, but the whole next and prev parts in mysql won't work because you can't map the keys it would require to track the fields properly because each link has to have an id in a database to link to. only thing I know of would be create the next/prev yourself and use some custom data persistence or data annotations. but the foreign key constraints I'm pretty sure on any relational database will prevent you from auto persisting those types of fields. reason being tracking deletes, inserts etc would be a nightmare because if you remove the middle of the chain, then the database has to try and guess where to link the ends to

How to set default values in Entity Framework 6 (Database First)

Background: I’m beginning a project to convert a web application using Linq2Sql to use Entity Framework (v6) instead. I have a lot of experience with L2S, but I’m brand-new to EF. Since our application and its database already exist, we’re using the “Database First” approach. Also, the database is evolving, so we’re making changes in the schema and the model is updated from the revised database, which regenerates code for the EF model each time.
For many of our entities (database tables), we set default values in our code whenever an entity is constructed. In Linq2Sql it’s easy: define a partial class for the entity, and add a method to the class like this:
partial void OnCreated() { SomeProperty = SomeDefaultValue; }
Whenever Linq2Sql constructs a new entity object, it calls the OnCreated() method you define, and the default values are set as desired. It works great.
The Problem: In EF, I don’t see a way to do this in a Database First scenario.
If I modify the model code generated by EF, the model code is overwritten whenever we update the model after a database revision.
If I define a partial class for the entity in a separate file and define a constructor, the compiler complains that the constructor is already defined.
There doesn’t seem to be any support for something like L2S's OnCreated() method, either.
Any suggestions?
EDIT: Thanks everyone for the helpful comments, but I think I need to point out an important consideration: My goal is to use the database-first approach and stick with it, rather than switching to code-first. When the database schema changes over time I want the EF Designer (or POCO Generator or whatever tools) to update my EF entity classes to match. All without losing my additions to initialize class properties when the class is constructed in the application. This is easy in Linq2Sql, but I just don’t see a way to accomplish this in EF database-first. All suggestions are welcome!
1 . Open .edmx file
2 . Select the field that has the default value and go to the properties
3 . then select StoreGeneratedPattern
4 . then change the value to Computed
i think it's worked.
OP here – I’ve given credit for the answer to ErikEJ but I’d like to recap what I’ve learned on this topic to share with others. There are three goals:
Use the database-first approach and stick with it, even as the database schema is changed over time. That is, have EF produce the code for each database table entity, based on a preexisting database, and update the code when the database is altered.
Provide a mechanism to initialize entity object properties each time the object is constructed, such as Employee.Dependents = 1, for example. (I know simple defaults can be set by the database schema, but more complex initializations must be executed by code.)
The custom initialization code must be preserved when the database schema is altered and EF regenerates the model code.
EF doesn’t provide a way to set properties each time an entity object is constructed in the database-first scenario. Editing the EF-generated code doesn’t work because it gets overwritten whenever EF regenerates the code after a change to the database schema. So far, four workarounds come to mind:
One idea is to add a constructor with more than the default zero-parameter constructor for each entity class. For example, c = new Customer(x) rather than the default c = new Customer(). Application code would call the new constructor, which would inherit the default constructor and add additional code to initialize the class properties. This avoids duplicating the default constructor, something that isn’t permitted by C#. The new constructor is in a separate partial class file, so it will not be overwritten when EF generates updated models from the database.
However, there is a risk that the application programmer may call the default constructor by accident, leading to subtle bugs.
Another solution is to wrap the entity classes in another class, say, a Customer2 class wrapped around the Customer class. The new class would inherit the original class and add initialization code for any properties as needed.
Since these new classes are separate from the original entity class code, they will not be overwritten by EF when it regenerates model code. It may be possible to hide the entity classes from the top-level application code, to avoid accidentally referring to the original classes by accident. If so, this should be a good technique, although I haven’t tested it yet.
A third-party tool, EntityFramework Reverse POCO Generator, is a help. It generates POCO model code much as EF does, but it is not EF. It has an option to generate partial classes, and the entity classes include a InitializePartial() method much like Linq2Sql’s OnCreated(). I think this will work fine for regenerating code as the database is altered over time. My concern here is that this is a third-party product, and there’s always a risk that it can become obsolete or unsupported.
Finally, you can alter the template that EF uses to generate code. The basic idea is to have the generated code add “partial void OnCreated()” to each class, and this lets us use the same convenient technique built into Linq2Sql. I assume newer versions of EF may overwrite the template changes, but it’s just one change in the template rather than changes to every entity class. This method is described here (How to efficiently set default entity values in Entity Framework 6, Database First) and the YouTube video is here (https://www.youtube.com/watch?v=i8J2ipImMuU).
Thanks to all who contributed! I hope this page is helpful to others, so you don’t have to burn as much time as I did looking for a solution.
Use the EF Reverse poco template- it will derive defaults from the database. You can override the InitializePartial method in your partial class to set defaults in code.
Coming from the EF background, I generally do it in the code first migration manually. In the up function of the generated migration, you can do something like this
AddColumn("dbo.Person", "IsActive", c => c.Boolean(nullable: false, defaultValue: true));
AddColumn("dbo.Person", "Name", c => c.String(nullable: false, defaultValue: "Mirza"));
Or to add default SQL value, use
AddColumn("dbo.Person", "CreatedDate",
c => c.String(nullable: false, defaultValueSql: "GETDATE()"));
However there's a downside of this approach in my opinion which is you have to keep a track of your (useless) migrations.
Just found this post looking for an answer to the same issue. Here's a work around that works for me.
Create a partial class for the entity (DB Table) you want to specify default values for, eg:
namespace myApplication.MyModel
{
public partial class myEntityName
{
public myEntityName(bool InitialiseOnConstruct) : this()
{
if (InitialiseOnConstruct)
{
this.property1 = defaultValue1;
this.property2 = defaultValue1;
}
}
}
}
Then in the code, to construct the entity:
thisEntity = new EntityName(true);
OK, it's an extra step, but it works. Hope that helps.

Where does the 'Name' property in a DBML come from?

I'm using Linq-To-Sql and inside my DBML there are objects built from the database connection provided.
If you click on an association line between two tables and view the properties on it, you will get the following:
Cardinality
Child Property
Access
Inheritance Modifier
Name
Parent Property
Access
Inheritance Modifier
Name
Participating Properties
Unique
My question is, where does Linq-To-Sql get the "Name" properties from? Where is the correlation to the actual database?
I ask this because if this table happens to be a parent to several children, Linq-To-Sql will just simply name these properties, "SomeParentName", "SomeParentName2", "SomeParentName3" , etc. So you'd have to go into the DBML and manually change these names to something meaningful every time you update this table.
Any help you can provide would be appreciated.
Part 2 of my question might be how do you guys handle these situations?
As for the Name: It takes the child / parent and comes up with something based on some internal voodoo. Don't ask me how.
As for Part 2: If you tend to have to redo stuff every time you update something I STRONGLY suggest switching to Entity Framework. It's very similar, but you can just hit "update" and your modifications are kept.

FluentNH mapping of a "deep" relational model to a "flattened" domain object

Here's the story: a Site (physical location of interest) has zero or more Contacts. Those Contacts are people associated with a Company who are authorized to deal with matters regarding the Site.
The schema looks like:
Person -< CompanyContact -< CompanySiteContact >- Site
||
| -< PersonPhone
|
-< PersonAddress
My entry point is Site. I need the list of Contacts. There is very little field data of interest until you get to Person. So, I'd like to collapse Person, CompanyContact and CompanySiteContact into one domain class.
The options I've come up with:
Create one domain class and use joins in the FluentNH map to flatten the layers as it retrieves the data
. It never sounded simple, and I'm running into problems with the multi-level join (if A joins B joins C, you can't specify the join to C within the join to B). I think, however, that if it's possible to specify the joins, that's just a one-time thing and so this will end up being the most maintainable solution.
Replicate the deep model in a set of "DTOs" that map 1:1 to the tables and can be passed to the constructor of a "flat" domain model. It works, but it feels like cheating (there is no problem that cannot be solved with another layer of abstraction, EXCEPT for having too many layers of abstraction), and my instinct tells me this will somehow eventually cause more problems than it solves.
Replicate the domain model 1:1 with the schema and use pass-through properties on CompanySiteContact to access properties down in the depths of a Person record. Again, works now, but it doesn't really solve the problem, and every new property that becomes of interest will require changes to the mapping, the actual domain class, AND the top-level domain class. Not very SOLID.
So, the Q is, how would I structure the mapping? Like I said, I'm not able to specify a join in a join. I think the way I have to do it is map the PK of each table, and use it in the next join from the top level, but I'm not exactly sure how to set that up (haven't used FluentNH to set up anything close to this complex before).
I'd recommend creating your domain model to closely match your database. From there I'd create DTOs and use AutoMapper to do the flattening. Easy.
Thanks to James for his answer; +1, but I don't think AutoMapper is necessary at this juncture, and I'm a little uneasy at including something that does the job quite that "automagically". I thought of a few more options:
Set up a view in the DB. This will work because due to business rules, the contact information is read-only; the app I'm developing must never update a contact directly because a different department maintains this rolodex.
Map my domain 1:1 as James suggested, but then use a Linq query to flatten the model into a DTO. This query can be encapsulated within a helper of the Repository, allowing developers to query the DTO directly using the same methods on the Repository as for other classes. It's more complex than the view with the same result, but it doesn't require schema changes.
I'll probably go with the first option, and resort to the second if necessary.

Entity Framework Complex Type vs Creating new Entity

I'm reading about the Entity Framework 4.0 and I was wondering why should I create a complex type and not a new Entity (Table) and a relation between them?
The perfect example is an address. Using a complex type for an address is much easier to deal with than a new entity. With complex types you do not have to deal with the Primary Key. Think about accessing an address how many common types of entities would have an address (Business Units, People, Places). Imagine populating many peoples addresses and needing to set a key for each one. With complex types you simply access the internal properties of they type and you're done. Here is an MSDN link of an example. http://msdn.microsoft.com/en-us/library/bb738613.aspx
This question has been here a while already, but I'm going to add an answer anyway in the hopes that the next poor sob that comes along knows what he's in for.
Complex types do not support lazy loading, at least not in EF 4.3. Let's take the address situation as an example. You have a Person table with 15 columns, 5 of which contain address information for certain individuals. It has 50k records. You create entity Person for the table with a complex type Address.
If you need a list of names of all individuals in your database you would do
var records = context.Persons;
which also includes addresses, pumping 5*50k values into your list for no reason and with noticeable delay. You could opt to only load the values you need in an anonymous type with
var records = from p in context.Persons
select new {
LastName = p.LastName,
FirstName = p.FirstName,
}
which works well for this case, but if you needed a more comprehensive list with, say, 8 non-address columns you would either need to add each one in the anonymous type or just go with the first case and go back to loading useless address data.
Here's the thing about anonymous types: While they are very useful within a single method, they force you to use dynamic variables elsewhere in your class or class children, which negate some of Visual Studio's refactoring facilities and leave you open to run-time errors. Ideally you want to circulate entities among your methods, so those entities should carry as little baggage as possible. This is why lazy loading is so important.
When it comes to the above example, the address information should really be in a table of its own with a full blown entity covering it. As a side benefit, if your client asks for a second address for a person, you can add it to your model by simply adding an extra Address reference in Person.
If unlike the above example you actually need the address data in almost every query you make and really want to have those fields in the Person table, then simply add them to the Person entity. You won't have the neat Address prefix any more, but it's not exactly something to lose sleep over.
But wait, there's more!
Complex types are a special case, a bump on the smooth landscape of plain EF entities. The ones in your project may not be eligible to inherit from your entity base class, making it impossible to put them through methods dealing with your entities in general.
Assume that you have an entity base class named EntityModel which defines a property ID. This is the key for all your entity objects, so you can now create
class EntityModelComparer<T> : IEqualityComparer<T> where T : EntityModel
which you then can use with Distinct() to filter duplicates from any IQueryable of type T where T is an entity class. A complex type can't inherit from EntityModel because it doesn't have an ID property, but that's fine because you wouldn't be using distinct on it anyway.
Further down the line you come across a situation where you need some way to go through any entity and perform an operation. Maybe you want to dynamically list the properties of an entity on the UI and let the user perform queries on them. So you build a class that you can instantiate for a particular type and have it take care of the whole thing:
public class GenericModelFilter<T> : where T : EntityModel
Oh wait, your complex type is not of type EntityModel. Now you have to complicate your entity inheritance tree to accommodate complex types or get rid of the EntityModel contract and reduce visibility.
Moving along, you add a method to your class that based on user selections can create an expression that you can use with linq to filter any entity class
Expression<Func<T, bool>> GetPredicate() { ... }
so now you can do something like this:
personFilter = new GenericModelFilter<Person>();
companyFilter = new GenericModelFilter<Company>();
addressFilter = new GenericModelFilter<Address>(); //Complex type for Person
...
var query = from p in context.Persons.Where(personFilter.GetPredicate())
join c in context.Companies.Where(companyFilter.GetPredicate()) on p.CompanyID = c.ID
select p;
This works the same for all entity objects... except Address with its special needs. You can't do a join for it like you did with Company. You can navigate to it from Person, but how do you apply that Expression on it and still end up with Person at the end? Now you have to take moment and figure out this special case for a simple system that works easily everywhere else.
This pattern repeats itself throughout the lifetime of a project. Do I speak from experience? I wish I didn't. Complex types keep stopping your progress, like a misbehaved student at the back of the class, without adding anything of essence. Do yourself a favor and opt for actual entity objects instead.
Based on Domain Driven Design Concepts, Aggregate root could have one or more internal objects as its parts. In this case, Internal objects - inside the boundary of Aggregate Root - does not have any KEY. The parent key will be applied to them or somehow like this. Your answer returns to the benefit of keeping all Parts inside Aggregate root that makes your model more robust and much simpler.

Categories