Asp.Net core Deleting an entry from table in database: what is the outcome - database

I have a database with table Photos and table Categories. Each photo is related to one category by categoryId field.
What happens when I delete one category from Categories table? Will the photos with that category be updated with a null value in the categoryID? Or how will entity-framework react to this change?
Another question can I then reset with a mass-change the values of those categories in the photos table? And how can I do that?

hi if you have created relationship between table(using foreign key) then only the deletion of parent table will affect deletion of child table. if you just created table separately and managing relationship with your code then it will not affect the child table. if you are creating using model first approach in entity framework with specifying relation then relationship will be automatically created in backend.
their are four options available in sql on deletion of parent entity
1)No Action
2)Cascade
3)SET NULL
4)SET Default
to know how it will affect check this article
https://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/

That would depend completely on how the ORM that is used defines the database model.
Assuming you use Entity Framework then you can define exactly how EF should react to that situation. In the DbContext you should find a OnModelCreating method in wich you can specify per table what restrictions you want on the table. There you can also define the behaviour of the OnDelete of a foreign key.
If you are not using EF but have your own or a different ORM then again, it depends on how that ORM is configured.
Simple check if you dont know about the used ORM is this: Does the field in the database have a foreign key and how is that configured? Also, is the field categoryID (as defined in the database) nullable? if so, then it apparently doesnt need the relation and shouldnt result in related deletes.

Related

Designing a database with similar, but different Models

I have a system whereby you can create documents. You select the document type to create and a form is displayed. Data is then added to the form, and the document can be generated. In Laravel things are done via Models. I am creating a new Model for each document but I don't think this is the best way. An example of my database :
So at the heart of it are projects. I create a new project; I can now create documents for this project. When I select project brief from a select box, a form is displayed whereby I can input :
Project roles
Project Data
Deliverables
Budget
It's three text fields and a standard input field. If I select reporting doc from the select menu, I have to input the data for this document (which is a couple of normal inputs, a couple of text fields, and a date). Although they are both documents, they expect different data (which is why I have created a Model for each document).
The problems: As seen in the diagram, I want to allow supporting documents to be uploaded alongside a document which is generated. I have a doc_upload table for this. So a document can have one or more doc_uploads.
Going back to the MVC structure, in my DocUpload model I can't say that DocUpload belongs to both ProjectBriefDoc and ProjectReportingDoc because it can only belong to one Model. So not only am I going to create a new model for every single document, I will have to create a new Upload model for each document as well. As more documents are added, I can see this becoming a nightmare to manage.
I am after a more generic Model which can handle different types of documents. My question relates to the different types of data I need to capture for each document, and how I can fit this into my design.
I have a design that can work, but I think it is a bad idea. I am looking for advice to improve this design, taking into account that each document requires different input, and each document will need to allow for file uploads.
You don't need to have a table/Model for each document type you'll create.
A more flexible approach would be to have a project_documents table, where you'll have a project_id and some data related to it, and then a doc_uploads related to the project_documents table.
This way a project can have as many documents your business will ever need and each document can have as many files as it needs.
You could try something like that:
If you still want to keep both tables, your doc_upload table in your example can have two foreign keys and two belongsTo() Laravel Model declarations without conflicts (it's not a marriage, it's an open relationship).
Or you could use Polymorphic Relations to do the same thing, but it's an anti-pattern of Database Design (because it'll not ensure data integrity on the database level).
For a good reference about Database Design, google for "Bill Karwin" and "SQL Antipatterns".
This guy has a very good Slideshare presentation and a book written about this topic - he used to be an active SO user as well.
ok.
I have a suggestion..you don't have to have such a tight coupling on the doc_upload references. You can treat this actually as a stand alone table in your model that is not pegged to a single entity.. You can still use the ORM to CRUD your way through and manage this table..
What I would do is keep the doc_upload table and use it for all up_load references for all documents no matter what table model the document resides in and have the following fields in the doc_upload table
documenttype (which can be the object name the target document object)
documentid_fk (this is now the generic key to a single row in the appropriate document type table(s)
So given a document in a given table.. (you can derive the documenttype based on the model object) and you know the id of the document itself because you just pulled it from the db context.. should be able to pull all related documents in the doc_upload table that match those two values.
You may be able to use reflection in your model to know what Entity (doc type ) you are in.. and the key is just the key.. so you should be able.
You will still have to create a new model Entity for each flavor of project document you wish to have.. but that may not be too difficult if the rate of change is small..
You should be able to write a minimum amount of code to e pull all related uploaded documents into your app..
You may use inheritance by zero-or-one relation in data model design.
IMO having an abstract entity(table) called project-document containing shared properties of all documents, will serve you.
project-brief and project-report and other types of documents will be children of project-document table, having a zero-or-one relation. primary key of project-document will be foreign key and primary key of the children.
Now having one-to-many relation between project-document and doc-upload will solve the problem.
I also suggest adding a unique constraint {project_id, doc_type} inside project-document for cardinal check (if necessary)
As other answers are sort of alluding to, you probably don't want to have a different Model for different documents, but rather a single Model for "document" with different views on it for your different processes. Laravel seems to have a good "templating" system for implementing views:
http://laravel.com/docs/5.1/blade
http://daylerees.com/codebright-blade/

TPT entities derived from TPH base classes in Entity Framework 6?

I have a project that is using EF6 Database first mapped to a SQL database. This is all new so I control the EF model as well as the database schema.
I currently have a table that I'll call Vehicle for simplicity. I use a discriminator column to get subclass Entities Car and Truck. This all works fine.
Now I need to do a 'soft delete' and move any deleted vehicles to a VehicleHistory table. (After trying this w/ EF i will probably use a SQL transaction). This needs to be reviewable so I need this history table mapped as well, but I would like to keep it within the inheritance hierarchy so its easily reused in other classes.
My idea was to create 'vehiclecurrent' and 'vehiclehistory' tables with FK's to Vehicle for shared columns. i would then use TPT in EF to get 'carcurrent','carhistory', ect... derived from my TPH classes(so e.g. carhistory->car->vehicle). This is not working and I get Error 3034: "Entities w/ different keys are mapped to the same row"
So my question is basically how can I pull this off? Will this approach work and how, or is there another way to accomplish this? Thanks!

Database "Identity" field and auto-increment

I'm writing my first database application and I've got an ambiguity I can't seem to find an answer for. I have an id field that is the identity set to auto-increment. My issue is trying to determine when the field is incremented. Is the field incremented when I call an instance of the object, when I call the AddObject method of the ObjectContext class, or when I call the SaveChanges method from an Entity model.
In my relational database each table has both a unique ID for that table and one that represents a group of users. After I create an instance of an object for that table I want to run a query (LINQ) that searches two tables to match two records and from one of those tables copy that group ID back to the individual user.
That or it is blatently obvious I know nothing about how relational databases work,
The identity field is handled by the database. It is created by the database when the row is inserted. The generated id is read back by SaveChanges and the entity object is updated.
WHen you add a new row to the database the counter is incremented.
If you have an ambiguity, this usually means that two tables fields are the same name, and your query doesn't know which one you want. Can be solved by defning which table the column is ment for.
I don't know LINQ, so hopefully someone can give you a more direct answer.

ADO.Net EF - how to define foreign key relation in model first approach?

I have been having previous issues regards to class inheritance and structuring a database around this and using the entity framework to no success. So I have tried to create the entities inside visual studio and see what database tables it creates automatically.
I have a Entity MediaItem which is Abstract and Game Inherits from this. Game has a Console (Int) which corresponds to ConsoleID. However, when I generate the database I get an extra unwanted column (ConsoleTypes_ConsoleID) inside MediaItems_Game table. Why is this and how can I prevent this from happening? Thanks.
First of all your model is probably wrong. ConsoleType and Game is not in one-to-one relation (unless you have single game for each console type). I expect 1 console can have multiple games. So it should be one-to-many. In reality game can be released on multiple platforms so it should be many-to-many.
You got unvanted column because your relation between ConsoleType and Game doesn't know that it should use Console property as a foreign key. This happens if you use independent association. Independent associations are used by default when you draw them from one entity to other entity in Entity designer. You must use foreign key association.
Start with this set up (draw association from ConsoleType to Game - you must have one-to-many relation):
Select relation between ConsoleType and Game an in properties click on Referential Constraint:
In Referential Constraint dialog just set up relation:
Save your model and generate database again.

How can I model non-matching Foreign Keys

I'm trying to use EF to model an existing SQL database. The DB is multi-tenant by having a clientID column in every single table (I cannot change this). I have table structure like the following.
Table 'ItemID' columns:
ClientID (pk)
ItemID (pk)
ItemName
Table 'Items' columns:
ClientID (PK)
ItemID (PK) [FK to ItemID.ItemID]
Version (PK)
ItemAttribute1
ItemAttribute2
ItemAttribute3
The DB is designed to store previous versions (rows) of the 'Item' object, hence the 'Version' column and PK.
I am new to the EF and trying to adopt it for my project. However, it seems that EF cannot handle this situation very well. I am open to all ideas including using stored procedures or views instead of access tables directly from EF. What about getting rid of the PKs and using 'independant' relations instead?
One specific problem I ran into is that EF (at least the designer) requires all PKs in one table be mapped to all PK columns in any related table. This does not make sense to me, as the example I've given will never work given that constraint. I am trying to make Items inherit from ItemID. The error I get is:
Error 3003: Problem in mapping
fragments starting at line 170:All the
key properties (ItemID.ClientID,
ItemID.ItemID) of the EntitySet ItemID
must be mapped to all the key
properties (Items.ClientID,
Items.ItemID, Items.Version) of table
Items.
I have been looking up all I can find on this topic and nothing has answered these questions for me. I appreciate any help. Thanks.
The error that you are getting from your EDM is coming from the fact that EF supports inheritance only if both entities have the exact same primary keys (hence a one to one relationship on database) so you cannot have inheritance between these 2 entities according to the current schema.
However, I don't see a problem on having a One to Many association between ItemID and Items entities and I believe this is the default EF behavior when you update your model from the database.
Please have a look at this post for more info:
Entity Framework, TPT Inheritance

Resources