Entity Framework lookup table - asp.net-mvc-4

I have 3 tables
Brands:
BrandID int
BrandName varchar(30)
Products
ProdID int
ProdName varchar(30)
BrandToProd:
BrandID int => FK Brands.BrandID
ProdID int => FK Products.ProdID
After generating model from existing database EF omits BrandToProd table and creates Many-To-Many relationships between Brands and Products. I would like to have third entity with following fields:
BrandName varchar(30)
ProductsName varchar(30)
This will give me possibility to use scaffolding for this entity. Ideally, when I'll add new pair of Brand and Product, EF should check first if such Brand or Product already exist in database (to avoid duplicates), if no, add to corresponding tables and that add mapping to BrandToProd table. If Brand or Product already exist, EF should you existing BrandID/ProdID value when adding to BrandToProd table. Is there any idea how to do that?

Your BrandToProd table is a pure junction table, i.e. a table with only two foreign keys. It is an EF feature to model such tables into a many to many association without a class in the conceptual model.
The easiest way to include a pure junction table in the model as an entity class is
add a dummy field to the database table temporarily
generate the model
delete the field from the database
update the model from the database
delete the property in the edmx diagram
An alternative way is to edit the edmx manually, but then you really need to know what you're doing. If you don't want to regenerate the model you could generate a second model and investigate the differences in both edmx files by a difference viewer.
However, I wonder if you need to do this. You seem to relate this to duplicate checking. But if you want to add a Brand or Product to the database you'll have to check for duplicates either way. If you want to add a new association (e.g. adding an existing Brand to Product.Brands) you don't have to check whether it exists. If it does, EF just ignores the "new" association.

As extra point to Gert's answer:
when using surrogate keys, there is always the issue of duplicate management. Normally there is 1 or more fields that make a logical key.
you can
a)create a unique index on the Db. Db will complain when the constraint is violated
b)Execute a logical duplicate check before attempting an insert.

I've ended up with just adding dummy ID field to my junction table, as I'm frequently changing DB schema (becsuse site development is in progress and I need from time to time update model from database) and don't want to each time remove/add dummy field to database. Another option I've used - SQL View on two tables and stored procedures mapped to corresponding actions (CRUD) in EF

Related

Postgres Foreign Keys on a generalizing link table

I'm doing some work with a system that has many types of entities that may or may not have access to many types of resources. Setting up these tables I have a structure where I set up an Entity_Sequence and a Resource Sequence, and then create a link table for each different entity and each different Resource to associate them with their respective sequence.
For example, I have a Users_Entities_Link table with the columns user_id referencing User, and entity_id, which is a bigint default nextval(Entity_Sequence).
To top this structure off is an Entities_Resources_Access of (entity_id, resource_id) to denote whether the entity has access to the resource. However, given that each of these entities could be related to any one of the entity link tables and the same for resources and each of the resource tables, I'm trying to figure out what the best way to handle the relationship is. This seems like a fairly rare problem, so I couldn't find help elsewhere on it.
The best that I could determine myself was to run an after deletion trigger on each of the Entity or Resource link tables that would check if the entity or resource exists in the access table, but that's a lot of debt to handle when adding in new potential entities or resources.
Is there a better solution to either the structural problem of how to deal with this many entities accessing many resources issue, or how to handle the sequence relationship better? Do I need to add in a dummy entity table and a dummy resource table that each only have an ID for the link and access tables to link foreign keys to? That seems like a lot of wasted space if I have a large quantity of any given entity or resource, and also something that I would have to manually unlink if it floated without anything referencing it on deletion of a row in an associated table (like a user)
Here's how the setup is currently designed:
Table some_entity_entity_link
some_entity_id FK refs some_entity(id)
entity_id not null default nextval(entity_sequence)
Table another_entity_entity_link
another_entity_id FK refs another_entity(id)
entity_id not null default nextval(entity_sequence)
Table some_resource_resource_link
some_resource_id FK refs some_resource(id)
resource_id not null default nextval(resource_sequence)
Table another_resource_resource_link
another_resource_id FK refs another_resource(id)
resource_id not null default nextval(resource_sequence)
Table entities_resources_access
entity_id
resource_id

Dynamics CRM 2011 Custom Entities: creating model that matches my SQL Server foreign and primary key relationships

I have a nice SQL Server DB setup with 2 tables with one to many relationship. Something like this:
TYPE:
ID Type
===========
1 mammal
2 fish
3 insect
PETS:
ID Name Foreign Key
=======================
1 Paris 1 (mammal)
2 Michael 2 (fish)
3 Mardy 1 (mammal)
How on earth do i recreate this in CRM? I know CRM likes to create its own primary key GUIDs and relalationship fields. I want to keep the integrity of my tabular relationships particularly due to the fact that i will be importing large amounts of data (1million + records) via a script on a regular basis rather than creating the records and relationships via the crm gui. Thanks.
In same situation, I created two entities with additional fields - integer ID. Relationship is CRM default one. If you want to 'keep' ID of 'Type' entity on 'Pets' form, you can add additional hidden field on Pets form (integer - Type_ID). And update this on Type change.
I think that this hidden Type_ID is not necessary if you will use these entities only from scripts. Maybe query performance will not be ideal, but this works :)
Edit: One more thing, if you need to generate IDs in CRM, you have to create plugin for generating unique ID, and which will be executed on entity create.
Hope it helps
Since CRM stores its PKs as GUIDs you can only define FKs only via those GUIDs.
As lazarus stated, create both Pets and PetTypes entities included an ExternalID int field.
Your import script needs to look up both GUIDs for every record to be imported:
read record
lookup PetTypes Guid for PetTypes.ExternalID = [pettype.id from record]
create if not exists
lookup Pets Guid for Pets.ExternalID = [id from record]
create if not exists
set Pets.PetTypes = new EntityReference() with PetTypes.ID (=guid)
save crm record

Use Foreign Key on SQL View in Entity Framework

I'm relatively new to Entity Framework.
I created a database with two tables: Accounts and Assignments.
Accounts has an AccountId primary key which is used as a foreign key in the Properties table. I really like that the Entity Framework automatically picks up the foreign key relationship and allows me to access rows in Assignments as a property of each row from Accounts.
I went ahead and created a new View object that returns all the columns from Accounts along with some other information. However, when I get the data from the View in SQL using the Entity Framework, it is no longer automagically referencing the associated rows in the Assignments table.
How can I get the desired behavior using Views with Entity Framework
This can work in EF, but the EF designer can't infer your FK out of the view, since the DB doesn't tell it where the FKs on view columns are (since they're naturally on the underlying tables, not the view itself).
You'll need to manually edit your EDMX, either via the designer or in XML, to get these properties.
The solution that worked for me was to include the appropriate data in the view so I didn't need to use the FK.
For example, include the PK's for the Assignment table in the view by adding the appropriate SQL to the view.
That way I could join to the view in LINQ without needing to refer to a generated property in the EDMX.

MVC3 Models, EF and SQL Relationship

I had a property in my MoveItems table called MoveItemSubCat. Up until now, I was thinking that I would provide a pre-populated dropdownlist of MoveItemSubCat, and the user would just select and it would go into DB.
So if the user already has an item with a MoveItemSubCat in the SQL DB, how would I make that the selected value in the view? Is this possible or do I need to make another table called MoveItemSubCats with all my SubCategories? This seems like it's going the way of a many-to-many relationship with a junction table of MoveItemSubCats_MoveItems.
Is a many-to-many the correct way to do this? Or can I get away with having a dropdownlistfor with values that go into 1 table column called MoveItemSubCat?
If you are planning to keep your db normalized, then you are going to want to go with a lookup table, for example:
MoveItemSubCat
-------------------------------
Id int
Code nvarchar(100)
If, in your original table, you change MoveItemSubCat to MoveItemSubCatId int, and make it a FK to the Id column in MoveItemSubCat, EF will pickup the relationship in your entity model and objects.

Inheritance in database?

Is there any way to use inheritance in database (Specifically in SQL Server 2005)?
Suppose I have few field like CreatedOn, CreatedBy which I want to add on all of my entities. I looking for an alternative way instead of adding these fields to every table.
There is no such thing as inheritance between tables in SQL Server 2005, and as noted by the others, you can get as far as getting help adding the necessary columns to the tables when you create them, but it won't be inheritance as you know it.
Think of it more like a template for your source code files.
As GateKiller mentions, you can create a table containing the shared data and reference it with a foreign key, but you'll either have to have audit hooks, triggers, or do the update manually.
Bottom line: Manual work.
PostgreSQL has this feature. Just add this to the end of your table definition:
INHERITS FROM (tablename[, othertable...])
The child table will have all the columns of its parent, and changes to the parent table will change the child. Also, everything in the child table will come up in queries to the parent table (by default). Unfortunately indices don't cross the parent/child border, which also means you can't make sure that certain columns are unique across both the parent and child.
As far as I know, it's not a feature used very often.
You could create a template in the template pane in Management Studio. And then use that template every time you want to create a new table.
Failing that, you could store the CreatedOn and CreatedBy fields in an Audit trail table referencing the original table and id.
Failing that, do it manually.
You could use a data modeling tool such as ER/Studio or ERWin. Both tools have domain columns where you can define a column template that you can apply to any table. When the domain changes so do the associated columns. ER/Studio also has trigger templates that you can build and apply to any table. This is how we update our LastUpdatedBy and LastUpdatedDate columns without having to build and maintain hundreds of trigger scripts.
If you do create an audit table you would have one row for every row in every table that uses the audit table. That could get messy. In my opinion, you're better off putting the audit columns in every table. You also may want to put a timestamp column in all of your tables. You never know when concurrency becomes a problem. Our DB audit columns that we put in every table are: CreatedDt, LastUpdatedBy, LastUpdatedDt and Timestamp.
Hope this helps.
We have a SProc that adds audit columns to a given table, and (optionally) creates a history table and associated triggers to track changes to a value. Unfortunately, company policy means I can't share, but it really isn't difficult to achieve.
If you are using GUIDs you could create a CreateHistory table with columns GUID, CreatedOn, CreatedBy. For populating the table you would still have to create a trigger for every table or handle it in the application logic.
You do NOT want to use inheritance to do this! When table B, C and D inherits from table A, that means that querying table A will give you records from B, C and D. Now consider...
DELETE FROM a;
Instead of inheritance, use LIKE instead...
CREATE TABLE blah (
blah_id serial PRIMARY KEY
, something text NOT NULL
, LIKE template_table INCLUDING DEFALUTS
);
Ramesh - I would implement this using supertype and subtype relationships in my E-R model. There are a few different physical options you have of implementing the relationships as well.
in O-R mapping, inheritance maps to a parent table where the parent and child tables use the same identifier
for example
create table Object (
Id int NOT NULL --primary key, auto-increment
Name varchar(32)
)
create table SubObject (
Id int NOT NULL --primary key and also foreign key to Object
Description varchar(32)
)
SubObject has a foreign-key relationship to Object. when you create a SubObject row, you must first create an Object row and use the Id in both rows