Saturday, December 26, 2015

MVC 5 Code First ApplicationDbContext throws error

In my MVC 5 Code First project I decided to put my domain tables under the out of box ApplicationDbContext


When I run the command "update-database ..." I got this error:
"Introducing FOREIGN KEY constraint 'FK_dbo.aaa_dbo.bbb_abcId' on table 'aaa' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors."

This is because I had not null 2 foreign keys in same table that both reference the primary key in same parent table. This creates 2 conflicting cascade delete paths. The solution is to make one of them nullable. See the source link:

Friday, December 25, 2015

mvc code first add foreign key referencing Asp.Net Identity ApplicationUser

in my case I have my own dbcontext called MyContext.

1. in the child class MyModel add:

public ApplicationUser User { get; set; }

2. in IdentityModels add below into class ApplicationDbContext

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasRequired(MyModel => MyModel.User);
            base.OnModelCreating(modelBuilder);
        }

3. for some reason this is not enough, the same code in 2. needs to be add into my own dbcontext too. So in MyContext add below

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasRequired(MyModel => MyModel.User);
            base.OnModelCreating(modelBuilder);
        }

in database it correctly generates the foreign key relationship as:

CONSTRAINT [FK_dbo.UserProfiles_dbo.AspNetUsers_User_Id] FOREIGN KEY ([User_Id]) REFERENCES [dbo].[AspNetUsers] ([Id])

Wednesday, December 23, 2015

Visual Studio 2015 Community MVC project could not open .cshtml views after installed github update

Visual Studio 2015 Community MVC project could not open .cshtml views after installed github update. Lucky found the solution here 

Step 1: remove everything under this folder C:\Users\abc\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache

 Step 2: reopen VS

TSQL: find out which table a constraint belongs to

TSQL: find out which table a constraint belongs to


SELECT
   OBJECT_NAME(o.parent_object_id)
FROM
   sys.objects o
WHERE
   o.name = 'ConstraintABC' AND o.parent_object_id <> 0