ASP.NET MVC Model First Many To Many - asp.net-mvc

I have some problems working with model first many to many relationship. Since I created many-many relationship between Town and Author via interface builder it created table TownAuthor with keys Towns_TownID and Authors_AuthorID but I want that just to be called TownID and AuthorID, how do I change that?
In Code first I would use that modelBuilder configuration in Context but I have no idea how to do this via model first...

You have to change the names of these columns in the Entity Designer DDL script (which is generated from the EDMX file and has ModelName.edmx.sql name) before executing it.
-- Creating table 'TownAuthor'
CREATE TABLE [dbo].[TownAuthor] (
[TownID] int NOT NULL,
[AuthorID] int NOT NULL
);
GO

Related

Add column to database without defining it in model with Entity Framework

Is it possible to add a column (or execute some SQL) to a table when Entity Framework is instantiating a new database, without defining it in the Model used in DbSet ?
Iam building a prototype for a SaaS application with Entity Framework and Elastic Scale Client, and want to use Row Level Security, for that a need a column to identify my tenants. So i figured it would be nice if I could use just the EF initializer to add this column, when adding new tenants to the system.
As noted in the documentation here, you can execute sql when you have the DBContext.
From the docs:
using (var context = new BloggingContext())
{
context.Database.ExecuteSqlCommand(
"UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1");
}
You could use this to modify the structure without having the actual structure defined in EF.

multilingual database schema for mvc dot.net model

We had developed in the past some sites, from company presentation sites to eshops, in classic asp. All of these was developed in multilingual environment (el, en) most of them. From database view we had choose the following schema. For example, for products table we have two related tables one with no lingual depended fields and one for lingual depended fields with one to many relation.
CREATE TABLE ref_language (
Code Char(2)NOT NULL,
Name Varchar(20) NOT NULL,
PRIMARY KEY (Code)
);
CREATE TABLE app_product (
Id Int IDENTITY NOT NULL,
PRIMARY KEY (Id)
);
CREATE TABLE app_product_translation (
ProductId Int NOT NULL,
LanguageCode Char(2) NOT NULL,
Description Text NOT NULL,
FOREIGN KEY (ProductId) REFERENCES app_product(Id),
FOREIGN KEY (LanguageCode) REFERENCES ref_language(Code)
);
To recreate the product model we use stored procedures to join the two tables for the requested language.
Now we want to move into dot.net mvc model. And we are wondering if there is a better approach, most suitable in mvc model.
It depends on your requirements, but you can just create a class to load and cache the captions in memory, loading them using EF. Either use a static class or preferably the ASP.NET cache.
If you are doing dynamic stuff on the client side then expose the strings through a MVC of WebAPI controller if necessary.
To make this easier I would decouple your translations from products in the schema. Make your translations universal.
Just have a single table called app_translation with Id, LanguageCode and Translation field. Then reference the Id on any table that needs a translated caption.
To enforce referential integrity, you can also have a app_translation_identifier table with a single column and a unique constraint. Then FK from the app_translation.Id to app_tranlsation_identifier.Id. And also have a unique key on app_translation for the Id and LanguageCode.

how to manage two EDMX files incase they have the same table name

I am working on an asp.net mvc web application,. i use the entity framework ADO.net entity data module to map two different databases and i have created two EDMX files. but unfortunately these databases have two tables with the same name UserGroup & Router. so i am unable to map these two tables inside the EDMX files, as entity framework will automatically delete the existing table which have the same name.
can any one advice how i can fix this , without having to rename the tables ?
You may change the name of the table on designer. Click the entity on designer and click and change the name property. Or you may have these two edmx in different name spaces (If it is possible)
Each EDMX file will have some namespace :
using DB1DBModel;
using DB2DBModel;
Class MyClass
{
void SomeMethod()
{
// table with same name MyTable in first edmx
DB1DBModel.EntitiesXYZ.MyTable=new DB1DBModel.EntitiesXYZ.MyTable();
// tables with same name MyTable in second edmx
DB2DBMode2.EntitiesABC.MyTable=new DB2DBMode2.EntitiesABC.MyTable();
}
}
// Hope this works

Newbie - combining parent and child views into one page

I am trying to learn mvc - I apologize in advance for all the silly questions. What I've done is created an mvc proejct based on an exsiting database, and then i've been disecting it to try to understand what's been created for me, and how to create my own stuff. Unfortunately, because I'm a new stackoverflow user, i can't post a picture of my project structure.
i have a parent controller and a child controller created using the wizard based on 2 separate tables i have in my model. I want to display both of them in one view - ultimately in a webgrid and be able to change data for any parent item, or child item. You can ignore the CombinedController for now. I've been doing some reading and i've learned that i should be creating a viewmodel that combines both the parent and child at the model level, and then go from there.
so i created this class:
Imports System.Data.Objects.DataClasses
Public Class ParentAndChild
Public Property myChildren As IEnumerable(Of Child)
Public Property myParent as Parent
End Class
I have a few questions:
Question 1
Do i have to add this ParentAndChild entity into the .edmx file in order to create a controller and view for it? I guess what I'm really asking is do i have to create a view in the sql database first, have the entity show up in the .edmx and then create a controller? Or can I just combine the two entities in a class? That's what i've done so far. I don't have a sql View in my database combining these two tables. The reason why I ask is because when i create my controller, if i want to get all the CRUD for free, i have to create using the Entity Framework. But I don't know what to specify for the data context.
Question 2
If i want a webgrid to somehow show all my parents and all their children, will the new ParentAndChild class work? I think that will only show the details for One parent and its children. I think i need to create a list of parents.. and then in the parentlist for each parent, add a collection of modules. But i don't know how to do this..
Question 3
How does the entityframework know which modules to return when i'm using my new class? I don't define the relationship anywhere... Is it because in the .edmx file, the system knows the relationships between the tables?
If you simply need to access the information of a parent entity and its child entity's you should be able to send your view the parent entity. A ViewModel is not absolutely necessary for this if Entity Framework knows about the relationship between the two entity's. If the relationship between the 2 tables exists at the database level then Entity Framework should have modeled it automatically.
An example of a controller would be:
public ActionResult Parent(int id)
{
var parent = context.Foo.Single(x => x.Id == id);
return View(parent);
}
If you need to create a table of all the child entity's you could do something like this:
#foreach(var item in Model.Children)
{
<td>#item.Property</td>
<td>#item.Property2</td>
}

Change model after database is created on EF4 code only

Hey, sorry for my bad english...
Using EF4 code-only, I have created some POCO classes and my database was generated from that. All worked fine, I inserted some data on the tables but now I need to create a new property on one of my classes. If i just create it, the application give me the exception:
{"The model backing the 'TestContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."}
I tried to create manually the field on the table, but it is still complaining... does someone know if there is a way and if so how can I manually update the database schema (i don't want to recreate it because i already have data) to match the model?
It should work if you make sure that your new column match exactly your new property.
For example, if you add a property NewProp
public class MyEntity
{
[Key]
public int Id;
public string PropA;
public int PropB;
public int NewProp;
}
then in your database table MyEntities, you would add a column NewProp of type int not null.
What you can do to check if the column you add is correct, is to rename your database, then let Code-First recreate the database and see what's different between the original and new databases.
EF generates partial classes. So you can add new properties(fields) in another partial class.

Resources