MVC3 Models, EF and SQL Relationship - sql

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.

Related

Proper Structure

I am building a webforms app using a 3 tier model and ado.net. (UI code behind) (middle tier 'classes') (DAL). Although EF would be a good fit, I would like to avoid it for this project as I am not familiar with it.
My database has a few tables and they have foreign key relationships between the tables. The app will have simple display, add, update, delete functions for each table.
I have created a class for each table that outlines the properties which correspond to each database column. So my question is how to handle the relationships between the tables, here is a simple example-
Table 'cars'
CarID
OwnerID
ColorID
Make
Model
Table 'Owners'
OwnerID
Fname
Lname
Table 'Colors'
ColorID
ColorName
On the Cars 'management' page -
The Owners and color tables should be represented as dropdownlists.
Do I load/bind the 'Owners' and 'Colors' lists with separate ado queries and simply save the 'IDs' of each field using the 'Cars' class or is there a way to tie these together, it seams there would be a more efficient way rather then making multiple database dips to pull the lists.
Any thoughts or comments welcome and appreciated.

Entity Framework lookup table

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

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.

Entity Framework and changing table schema/structure

I was wondering if someone knows if the following is somehow possible using EF or some other ORM.
We have a number of tables in a database. Like this one "Person"
Id
Name
Phone
Email
This is the same for all databases and will not change, it's our base table so to speak :)
Now one database might have a table also called "Person", it's the same but with an extra column Phone.
Id
Name
Phone
Email
Phone
Is there a way to have the Phone column available in the entity like a Dictionary<string,object>? I am actually only looking for basic select queries to support this. So I won't need a separate model for all databases.
Or is it just not possible? :)
--
Christian
Linq To Sql or Linq To Entities are designed to work on static table schema, I'm afraid you'll have to use ADO.NET to get what you want, or go to another schema (FK from some other tables containing key values pairs for exemple)

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