Sequelize associate a table without defining its schema - postgresql

Lets say I have a table in the DB called departments, In my code I don't need to interact directly with it and its schema is defined as a part of another service.
I want to make a new table called employees that will have a foreign key from departments.
Is there a way to make this association (referencing the table) without needing to defining the table schema again in my project?

To the best of my knowledge, there is no way to define an association between two tables one with a model defined in Sequelize and the other with no model defined in Sequelize.
To define an association between two models you must define their respective models in Sequelize.

Related

Entity Framework 'Update Model from Database' recreating associations between base and sub classes

I am trying to implement a number of base/sub classes using Entity Framework, database first. Following some online tutorials, I have decided to attempt TPT inheritance.
On the database, I have a base class table 'Location', and two sub class tables: 'StreetAddress' and 'RuralRouteAddress'. I have defined a foreign key constraint between the sub class tables and the base class table on their primary keys. 'Location's Primary Key is an auto-increment column, and the two sub class tables' primary keys are not auto-increment.
In Entity Framework, I defined the 'Base Type' of the two sub classes as 'Location'. I then deleted the associations (and their corresponding navigation properties) from the model. I also deleted the ID column mappings from the sub classes, as ID is now inherited from the 'Location' base class.
This seems to have worked. I haven't tried updating/inserting, but querying returns the data with proper inheritance in place.
My problem is that, whenever I 'Update Model from Database', he inheritance association lines stay, but the FK associations between the base class and the sub classes are brought back... . I then have to delete them, and realign the association lines on my diagram (I'm a bit picky about the layout of the model diagram).
This isn't so bad, but the project that I would like to use TPT inheritance in has a lot of inheritance. Having to delete a ton of associations and reorganize my entire diagram every time I update the model is not very appealing.
Did I do something wrong when I implemented inheritance? Is there a way to ignore/exclude certain associations from being created when updating the model?
The relationships you define in the database will always reappear when you update the model from the database. This is by design. If you want to have classes in the model that have a different relationship structure, try creating a complex model from a stored procedure that selects all the columns (or all the columns you want) from the base table. Import that procedure and in the Function Imports, edit the return type by creating a new complex type, or even just renaming the result that EF automatically creates. Then add your associations on that type, and use it as the base type for your inherited classes.
The good part of this is that you can adjust the type structure to match any table changes by editing the stored procedure, then using "Get Column Information" and "Update" to bring the complex type into line. It won't overwrite your associations because they aren't defined in the database, but it is almost as straightforward as using TPT.
Joey

Entity Framework: Doing JOINs without having to creating Entities

Just starting out with Entity Framework (Code First) and I have to say I am having a lot of problems with it when loading SQL data that is fairly complex. For example, let's say I have the following tables which stores which animals belongs to which regions in the world and the animal are also categorized.
Table: Region
Id: integer
Name string
Table AnimalCategory
Id integer
Name: string
RegionId: integer -- Refers back Region
Table Animal
Id integer
AnimalCategoryId integer -- Refers back AnimalCategory
Let's say I want to create a query with Entity Framework that would load all Animals for a specific region. The easiest thing to do is to create 3 Entities Region, AnimalCategory, and Animal and use LINQ to load the data.
But let's say I am not interested in loading any AnimalCategory information and define an Entity class just to represent AnimalCategory so that I can do the JOIN. How can I do this with Entity Framework? Even with many of its Mapping functions I still don't think this is possible.
In non Entity Framework solutions this is easy to accomplish by using INNER JOINs in SPs or inline SQL. So what are my options in Entity Framework? Shall I pollute my data model with these useless tables just so I can do a JOIN?
It's a matter of choice I guess. EF choose to support many-to-many associations with transparent junction tables, i.e. where junction tables only have two foreign keys to the associated entities. They simply didn't choose to support this far less common "skipping one-to-many-to-many" scenario in a similar manner.
And I can imagine why.
To start with, in a many-to-many association, the junction table is nothing but that: a junction, an association. However, in a chain of one-to-many (or many-to-one) associations it would be exceptional for any of the involved tables to be just an association. In your example...
Animal → AnimalCategory → Region
...AnimalCategory would only have a primary key (Id) and a foreign key (RegionId). That would be useless though: Animal might just as well have a RegionId itself. There's no reason to support a data model that doesn't make sense.
What you're after though, is a model in which the table in the middle does carry information (AnimalCategory.Name), but where you'd like to map it as a transparent junction table, because a particular class model doesn't need this information.
Your focus seems to be on reading data. But EF has to support all CRUD actions. The problem here would be: how to deal with inserts? Suppose Name is a required field. There would be no way to supply its value.
Another problem would be that a statement like...
region.Animals.Add(animal);
...could mean two things:
add an Animal and a new AnimalCategory, the latter referring to the Region.
Add an Animal referring to an existing AnimalCategory - without being able to choose which one.
EF wouldn't want to choose for some default behavior. You'd have to make the choice yourself, so you can't do without access to AnimalCategory.

Adding DateTime field to many-to-many EF Code First relationship

I am using EF 6 Code-First, table per type, and I have two concrete classes Group and User. Group has a navigation property Members which contains a collection of User. I have mapped this many-to-many relationship in EF using Fluent syntax:
modelBuilder.Entity<Group>
.HasMany<User>(g => g.Members)
.WithMany(u => u.Groups);
I would like to be able to say when a member has joined a group so that I can query for, say, the newest member(s). I am not sure of how this is best accomplished within the framework.
I see the following options:
Create and use an audit table (ie GroupMembershipAudit consisting of Group, User, join/unjoin, and DateTime
Add a column to the autogenerated many-to-many table between User and Group
Is there anything within EF to facilitate this sort of storage of many-to-many historical info like this / append columns to the many-to-many relationship?
Add a column to the autogenerated many-to-many table between User and
Group
That is not possible - auto-generated junction tables can contain only keys (that is called Pure Join Table). According to Working with Many-to-Many Data Relationships article: If the join table contains fields that are not keys, the table is not a PJT and therefore Entity Framework cannot create a direct-navigation (many-to-many) association between the tables. (Join tables with non-key fields are also known as join tables with payload.)
Create and use an audit table (ie GroupMembershipAudit consisting of
Group, User, join/unjoin, and DateTime
Actually you should create GroupMembershipAudit entity. With Code First table will be generated, you don't need to create it manually.

Where to place auditing fields?

In our shop, when we design a database, we typically include auditing attributes for each table (LastUpdateUser, LastUpdateDate, etc). This is common practice, however, I've noticed this becoming an increasing problem when you have tables that "inherit" from other tables, especially using tools such as the entity framework.
For example, if you have tables Customers and Employees, and those tables have a foreign key to table People, then in your entity / class model when you establish the inheritance, you need to change the names for the audit fields because they exist in both tables. Perhaps they need to become PersonLastUpdatedUser and PersonLastUpdatedDate, while the ones from Employees remain as simply LastUpdatedUser and LastUpdatedDate.
When designing tables for inheritance, do you put such audit fields in both tables, or do you just have them in the parent table and update the parent table whenever an attribute changes in a child table?
If you want to use inheritance than those attributes belong to parent table because the parent with related table forms single entity and you track auditing for whole entity. If you for any reason needs those attributes in both tables it should be the first warning that those tables are not good candidates for inheritance.
If you want true auditing, you create separate audit tables that are populated by triggers (never ever by the application or you will miss items that need to be audited).
and they shouw both the old and new value as well as the date and the user or application that made the change.
If you want a last updatedcolumn in each table (which I think is better than having it only in the parenta as that doesn't tell you anything about which of the tables changes last) and you want o use inheritance then you might need to create unique names by adding the table name to lastUpdated. So PersonLastUpdated and OrderLastUpdated, etc.
Or you don't use inheritance.

Model a 1-to-many relationship with a single table in Entity Framework

Lets say I have 2 tables on my physical model, Receipt(ID, Location) and LineItem(ID, ReceiptID, ItemName) where a Receipt has multiple LineItems and ReceiptID is a Foreign Key to Receipt's ID.
I want to model these as a single table in my conceptual model, where I only see a table of LineItems with the Location included on each LineItem.
Every time I try to model this in the Entity Modeler, I get an error about how the Primary Key must be the same for every table being combined into the single conceptual entity.
Is this even possible to model using the entity framework?
Thanks!
No there is no way to model this directly. You must either create database view and map that view or import both entities and create QueryView in the model. In both cases resulting entity combining your two tables will become readonly and the only way to support CUD operations will be mapping stored procedures.