Many to Many Relationship Entity Framework - c#

Well, I have tried to do a Many-to-Many relationship using Entity framework, where the Join table has more than just two ID, it will have two other columns Active and DateUpdate. So here is the designer.
Tables Design
When I did the context importing from an existing database, it look to work well. But I got a big question, is it right have the direction going from Group[0].GroupUser[0].User and going back in the same case? And in that way creating a lot of redundancy has showed in the picture below? Or is it something wrong?
Redundancy

It is not redundancy. Group[0].GroupUser[0].User is a reference to User and User has a navigation property to the GroupUser. Therefore, when you see User and then navigate to GroupUser of that user, the GroupUser will have a reference to User. If you keep expanding, it will keep showing you the same User and GroupUser.

Related

On the "owned" types in EF Core

In my project, I use the EF Core fluent config, code first. I read a little about the owned types, but the situation bellow is not really clear to me:
Suppose I have a Project entity and a ProjectType.
Should I map that property as :
Entity<Project>.HasOne<ProjectType>(); or rather as
Entity<Project>.OwnsOne<ProjectType>();
The ProjectType entity should be mapped to a table ProjectType(ProjectTypeId, Name, Description)
As I read, owned are
"types that can only ever appear on navigation properties of other
entity types. These are called owned entity types. The entity
containing an owned entity type is its owner. Owned entities are
essentially a part of the owner and cannot exist without it"
In my case
"ProjectType can only ever appear on navigation properties of Project entity type. ProjectType is essentially a part of the Project and cannot exist without it"... however, in order to create a separate table, as I understood I need to use HasOne, not OwnsOne... would be great if someone explain better this idea. Thanks a lot.
ProjectTypes sound like a reference table that might otherwise be modifiable over the course of an application's lifespan, such as through a system administration role. Usage of the new "Owns" is a convention to help enforce concepts like type-specific composition, and linking tables in a relational data model.
A better example for composition: Say you have a Project and as a part of a Project there are some details that are fairly large, and infrequently used. Things like an image or other binary data, or perhaps some large text. Having these BLOB/CLOB details inside the Project table can be a recipe for disaster when you fetch a Project, or many Projects, so you normalize them out into a separate related table called ProjectDetails, or possibly several related tables. This way, for the most part when you are working with Project and loading those entities you don't have to worry about pulling back these large fields all of the time, you can reference a ProjectDetails to include only when it is actually needed. Since ProjectDetails doesn't really serve any purpose on it's own, it doesn't need a DbSet or anything of the like, so we can set up the relationship from Project to OwnsOne ProjectDetails.
ProjectType on the other hand would potentially have a DbSet to establish new project types over the course of configuring an application. You may also want to associate other project-related details based on a Project Type. In this case it would make more sense for Project to HasOne ProjectType. We can have a DbSet of ProjectTypes to manage, and other entities may filter by ProjectTYpe as well, Project Stages/Phases, etc.
As far as the database schema goes between Owns and Has, there is no difference. It's solely about how the EF DbContext will expect to work with the entities.
Other common examples of using Owns are linking tables. For instance you have an Address table which is shared between Orders, Customers, etc. Neither "Owns" addresses, but they do own their linking table: Order Owns OrderAddress, Customer Owns CustomerAddress. These entities "Has" an Address. We may still want to review Addresses as they represent physical locations and there is a difference between associating an Order etc. to a different location, and "adjusting" the details recorded for a physical location. (I.e. correcting a street name or municipality) There is not a need to ever deal with OrderAddresses or CustomerAddresses outside of the scope of the Order or Customer respectively.

Incremental ETL on code first many-to-many association table

I'm setting up a data warehouse (in SQL Server) together with our engineers we got almost everything up and running. Our main application also uses SQL Server as backend, and aims to be code first while using the entity framework. In most tables we added a column like updatedAt to allow for incremental loading to our data warehouse, but there is a many-to-many association table created by the entity framework which we cannot modify. The table consists of two GUID columns with a composite key, so they are not iterable like an incrementing integer or dates. We are now basically figuring out the options on how to enable incremental load on this table, but there is little information to be found.
After searching for a while I mostly came across posts which explained how it's not possible to manually add columns (such as updatedAt) to the association table, such as here Create code first, many to many, with additional fields in association table. Suggestions are to split out the table into two one-to-many tables. We would like to prevent this if possible.
Another potential option would be to turn on change data capture on the server, but that would potentially defeat the purpose of code first in the application.
Another thought was to add a column in the database itself, not in code, with a default value of the current datetime. But that might also be impossible / non compatible with the entity framework, as well as defeating the code first principle.
Are we missing anything? Are there other solutions for this? The ideal solution would be a code first solution, or a solution in the ETL process without affecting the base application, without changing too much. Any suggestions are appreciated.

Delete all One to Many associated items - Telerik OpenAccess ORM

Using Telerik OpenAccess ORM I have 2 objects User and Investment. More specifically Investments contains a foreign key to User as any typical one to many relationship. In other words each User can have mutliple Investments but each Investment can only have one user.
I have then attempted to utilize the open access feature 'Is Managed'
Which should mean that I can do something like User.Investments.Clear(); and it deletes all the related investments (or at least this works fine in many-to-many relationships) but unfortunately when I attempt this I am greeted with the following error.
"Update failed: Telerik.OpenAccess.RT.sql.SQLException: Cannot insert
the value NULL into column 'UserID', table
'CODECorp.dbo.Investment'; column does not allow nulls. UPDATE
fails."
Clearly what the ORM is trying to do is remove the association (i.e. foreign key) from the investment object to the user rather than deleting it. I have confirmed this by running SQL profiler and can see that it's running an Update rather than a Delete.
So what am I missing here? Why is it incorrectly trying to remove the association rather than simply deleting the row as you would expect?
By design, the behaviour of the navigation properties with IsManaged set to True, in scenarios where a child object is deleted from the collection of the parent object, is to remove the relationship between the two objects. In other words, Telerik Data Access (previously known as Telerik OpenAccess ORM) will keep the child record in the database but will generate a statement that attempts to set the foreign key to NULL.
A solution in this situation would be to pass the collection to the Delete method of the context. For example:
dbContext.Delete(User.Investments);
dbContext.SaveChanges();
This will produce the necessary DELETE statement. More details about the management of navigation properties with Telerik Data Access is available in this documentation article.
I hope you find this feasible. I am looking forward to your feedback.

Implementing in-memory instances of an object in NHibernate

Is there anyway to implement in-memory or fixed/hardcoded object instances in NHibernate that appear to all intents and purposes to be real instances of the object read from the database?
I have a historical database that has a number of missing foreign key values against a number of different tables as they are fixed/hard coded in the old DAL.
This is causing me problems in my NHibernate mapping.
An example of this would be a fixed immutable user, say 'ADMIN' that exists in code but not in the database. This 'ADMIN' user is still used in various foreign keys so needs to exist in NHibernate so that it can manage the FK mapping.
I've managed cheat loading by using a sql view which has the hard coded rows explicitly added, but of course I can't write to a view like that so need an alternative solution.
I did find a reference to the uNhAddIns WellKnowInstanceType that seems to do something similar, but I couldn't get to to work.
Anyone have any alternative suggestions?
one trick i can think of is attaching the imaginary User instance to the session befor querying using sess.Lock(admin, LockMode.None); that should take care of the reference. But I#m not sure what happens when eager loading the reference.

Get Number of Entities and its Fields Programmaticaly, Data-driven Application

I want to create a dynamic datadriven application for practice purposes.
If I have a Modell with a Entity and I need a new one, then I want to create it only in the Diagram (modell) and thats all.
Everything else should be done dynamically, adding the new entity to b.e a Listbox, make it clickable and create a "Show Datas" and a "New/Edit" Tab with the right labels and textboxes in it. (For editing/creating new)
What I would like to know is, how can I:
Get the number of the entities
Is it possible to update the database, without needing to delete it and create new (Else I would loose all Data), if hopefully yes, how?
Get all the fields from a Entity? (Do I must work here with Reflection?)
Hope someone could help
1.Get the number of the entities
Using Context object you get the list of entities. there you can use the .Count() to check the no of entities of that type.
2.Is it possible to update the database, without needing to delete it and create new (Else I would loose all Data), if hopefully yes, how?
This question is little unclear. you want to delete database.. or entity?? you can do any operation on entities that will be reflected on back end if you want. Regarding database delete and create operation, entity framework is not designed for.
Yes you can add new entity to model and then map it with the back end tables.. it is possible to modify the model as per your backend. Even you can create you custom entites that reflect operation on multiple tables on the database but with some care about data integration.
3.Get all the fields from a Entity? (Do I must work here with Reflection?)
Yes.. To access the properties of Entity with out knowing their name you should go through reflection.

Categories