EntityFramework updating model from database results in mapping file not created - c#

I am having some trouble adding a table to my data entity model.
EntityFramework 6.1.3 installed
VS Enterprise 2017 15.9.3
Repro steps:
I open my Model.edmx
Right click > Update Model From Database
Add Table > select my table > Finish
And when I go into Model.Context.cs I see this line for my newly added table:
modelBuilder.Configurations.Add(new MyTable_Mapping());
but the MyTable_Mapping is underlined and complains the file is missing.
And inside Model.Mapping.cs reads
ErrorGeneratingOutput
My table schema:
CREATE TABLE [dbo].[MyTable](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[AccountUserId] [int] NOT NULL,
[MFAUserId] [bigint] NOT NULL,
[LastAuthDate] [datetime] NOT NULL,
[CreateDate] [datetime] NOT NULL,
[StatusId] [int] NOT NULL,
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Related

Unable to track an instance of type ** because it does not have a primary key. Only entity types with primary keys may be tracked

Having an issue with a specific table on my project which is driving me up the wall.
I am trying to delete all the entries where from a table where the eventUId is something.
so my code is this
var SessionsToRemove = _context.Connlog.Where(s => s.Eventuid == EventDetails.Uid);
_context.Connlog.RemoveRange(SessionsToRemove);
_context.SaveChanges();
My table on SQL server has a KEY which is defined to the column ID.
This works on all the other tables, except for this one.
Can someone please help me?
#Caius
USE [vents]
GO
/****** Object: Table [dbo].[Connlog] Script Date: 17/02/2021 12:46:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Connlog](
[id] [int] IDENTITY(1,1) NOT NULL,
[uid] [nvarchar](max) NULL,
[chatconnid] [nvarchar](100) NULL,
[connstart] [datetime] NULL,
[connend] [datetime] NULL,
[useremailaddress] [nvarchar](500) NULL,
[eventuid] [nvarchar](500) NULL,
CONSTRAINT [PK_Connlog] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
EDIT:
After the last edit, I've decided to scaffold the database again which sorted the the issue.
Thank you guys for your help.

Migrate Users ASP.NET Web Pages tables to MVC 6

Info
I want to 'upgrade' my ASP.NET Web Page project to an ASP.NET MVC project by just starting over, it are only a few pages and it would be good for learning.
The Issue
The current project holds a few users for authentication
ASP.NET made a few tables in my database:
Roles
Profiles
Users
...
But when I use the MVC Project I see it makes different tables for authentication:
AspNetUserLogins
AspNetUserRoles
AspNetUser
...
The Question
How do I migrate my users or how do I tell ASP.net to use the old tables?
Greetings you may want to start with Database first Approach in MVC-Core but its little bit different from what you have seen so far, let me explain the steps for adding your database:
Install Entity Framework:
Run Install-Package Microsoft.EntityFrameworkCore.SqlServer
To enable reverse engineering from an existing database we need to install a couple of other packages too.
Run Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
Run Install-Package Microsoft.EntityFrameworkCore.Design
Run Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design
Now Reverse engineer your model:
Run the following command to create a model from the existing
database. If you receive an error stating the term
'Scaffold-DbContext' is not recognized as the name of a cmdlet, then
close and reopen Visual Studio.
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=DataBaseName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
The reverse engineer process created entity classes and a derived context based on the schema of the existing database. The entity classes are simple C# objects that represent the data you will be querying and saving. And now you can create a DbContext class and start using your database, so far you issue about database is over, and now i suggest you read about Identity In Asp.NET Core.
I came across this site thanks to this blog
And edited to fit my needs:
/****** Object: Table [dbo].[AspNetRoles] Script Date: 11/14/2013 1:56:03 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID('dbo.AspNetUserRoles', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetUserRoles]
GO
IF OBJECT_ID('dbo.AspNetUserLogins', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetUserLogins]
GO
IF OBJECT_ID('dbo.AspNetUserClaims', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetUserClaims]
GO
IF OBJECT_ID('dbo.AspNetRoles', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetRoles]
GO
IF OBJECT_ID('dbo.AspNetUsers', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetUsers]
GO
CREATE TABLE [dbo].[AspNetUsers] (
[AccessFailedCount] INT NOT NULL,
[Email] NVARCHAR (MAX) NULL,
[EmailConfirmed] BIT DEFAULT ((0)) NULL,
[Id] NVARCHAR (128) NOT NULL,
[LockoutEnabled] BIT DEFAULT ((0)) NULL,
[LockoutEndDateUtc] DATETIME2 (7) NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT DEFAULT ((0)) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[TwoFactorEnabled] BIT DEFAULT ((0)) NULL,
[UserName] NVARCHAR (MAX) NULL,
[CreateDate] DATETIME NULL,
[ConfirmationToken] NVARCHAR (128) NULL,
[IsConfirmed] BIT DEFAULT ((0)) NULL,
[LastPasswordFailureDate] DATETIME NULL,
[PasswordFailuresSinceLastSuccess] INT DEFAULT ((0)) NULL,
[PasswordChangedDate] DATETIME NULL,
[PasswordVerificationToken] NVARCHAR (128) NULL,
[PasswordVerificationTokenExpirationDate] DATETIME NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE TABLE [dbo].[AspNetRoles] (
[Id] NVARCHAR (128) NOT NULL,
[Name] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE TABLE [dbo].[AspNetUserRoles] (
[UserId] NVARCHAR (128) NOT NULL,
[RoleId] NVARCHAR (128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED ([UserId] ASC, [RoleId] ASC),
CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[AspNetRoles] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_RoleId]
ON [dbo].[AspNetUserRoles]([RoleId] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_UserId]
ON [dbo].[AspNetUserRoles]([UserId] ASC);
GO
CREATE TABLE [dbo].[AspNetUserLogins] (
[UserId] NVARCHAR (128) NOT NULL,
[LoginProvider] NVARCHAR (128) NOT NULL,
[ProviderKey] NVARCHAR (128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED ([UserId] ASC, [LoginProvider] ASC, [ProviderKey] ASC),
CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_UserId]
ON [dbo].[AspNetUserLogins]([UserId] ASC);
GO
CREATE TABLE [dbo].[AspNetUserClaims] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[ClaimType] NVARCHAR (MAX) NULL,
[ClaimValue] NVARCHAR (MAX) NULL,
[UserId] NVARCHAR (128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_User_Id] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_User_Id]
ON [dbo].[AspNetUserClaims]([UserId] ASC);
GO
INSERT INTO AspNetUsers(Id, UserName, PasswordHash, SecurityStamp,
CreateDate, ConfirmationToken, IsConfirmed, LastPasswordFailureDate, PasswordFailuresSinceLastSuccess,
PasswordChangedDate, PasswordVerificationToken, PasswordVerificationTokenExpirationDate,AccessFailedCount,LockoutEndDateUtc)
SELECT Users.UserId, Users.UserName, Memberships.Password,
Memberships.PasswordSalt, CreateDate,
null, 1, '1/1/1977', 0,
'1/1/2017', null, '1/1/2100',0,'1/1/1977'
FROM Users
LEFT OUTER JOIN Memberships ON Users.UserId = Memberships.UserId
GO
INSERT INTO AspNetRoles(Id, Name)
SELECT RoleId, RoleName
FROM Roles
GO
INSERT INTO AspNetUserRoles(UserId, RoleId)
SELECT UserId, RoleId
FROM UsersInRoles
GO
--INSERT INTO AspNetUserLogins(UserId, LoginProvider, ProviderKey)
--SELECT UserId, Provider, ProviderUserId
--FROM Memberships
--GO

Entity Framework is not identifying primary key defined in database table

CREATE TABLE [Admin].[PlanManagers]
(
[ID] [bigint] IDENTITY(10000,1) CONSTRAINT PK_PLANMANAGERS Primary key NOT NULL,
[AdminUserId] [bigint]
CONSTRAINT FK_ADMINUSER_PLANMANAGERS
FOREIGN KEY REFERENCES [Login].[AdminUsers]([Id])
ON DELETE SET NULL NULL,
[PlanName] [nvarchar](255) NOT NULL,
[PlanIntro] [nvarchar](max) NULL,
[Active] [bit] Default(0) NOT NULL,
[Created] [datetime] Default(getutcdate()) NOT NULL,
[Updated] [datetime] Default(getutcdate()) NOT NULL,
[LastUpdatedBy] [BIGINT] NOT NULL,
)
I have added an Entity Framework Data Model for this database table but Entity Framework doesn't recognize the primary key.
I have manually mentioned the ID [Key] using data annotations.
What is the most possible cause of the bug..

How to FIX this message in ASP.NET (Visual Studio) with my query?

This is my script in SQL but when I try use a form view in ASP.NET (visual studio). I worked with SQL Server Management Studio
CREATE TABLE [odl].[MaterialDetail]
(
[Material] [nvarchar](50) NOT NULL,
[PlantID] [nvarchar](50) NOT NULL,
[LabelPos] [char](1) NOT NULL,
[UseProdLabel] [tinyint] NOT NULL,
[UseContLabel] [tinyint] NOT NULL,
[UseTote] [tinyint] NOT NULL,
[COO] [nvarchar](50) NOT NULL,
[LabelsPerCont] [decimal](9, 2) NOT NULL,
[TareWeight] [decimal](9, 2) NOT NULL,
[AltTareWeight] [decimal](9, 2) NOT NULL,
[ModDate] [datetime] NOT NULL,
[CreateDate] [datetime] NOT NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
CONSTRAINT [PK_MaterialDetail] PRIMARY KEY CLUSTERED
(
[Material] ASC,
[PlantID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_Material] DEFAULT ('') FOR [Material]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_PlantID] DEFAULT ('') FOR [PlantID]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_LabelPos] DEFAULT ('0') FOR [LabelPos]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_UseProdLabel] DEFAULT ((0)) FOR [UseProdLabel]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_UseContLabel] DEFAULT ((1)) FOR [UseContLabel]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_UseTote] DEFAULT ((0)) FOR [UseTote]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_COO] DEFAULT ('') FOR [COO]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_LabelPerCont] DEFAULT ((2)) FOR [LabelsPerCont]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_TareWeight] DEFAULT ((0)) FOR [TareWeight]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_AltTareWeight] DEFAULT ((0)) FOR [AltTareWeight]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_ModDate] DEFAULT (getdate()) FOR [ModDate]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_CreateDate] DEFAULT (getdate()) FOR [CreateDate]
GO
ALTER TABLE [odl].[MaterialDetail] ADD CONSTRAINT [DF_MaterialDetail_rowguid] DEFAULT (newsequentialid()) FOR [rowguid]
GO
I get this error in the moment when i try test my query
There was an error executing the query. Please check the syntax of
the command and if, present, the types and values of the parameters
and ensure they are correct Invalid object name 'MaterialDetail'
First of all, that SQL code doesn't produce any data or results. It just sets up a brand new empty table. I don't know what you'd expect your form-view to show, because there's not data here.
Secondly, if the table already exists in the database, or if the constraints you are adding already exist, I would expect this code to throw an error when run for a second time, because you are trying to create an object that already exists.
Finally, that SQL makes extensive use of the GO separator. GO is not a part of the SQL language. It is a feature of Sql Server Management Studio that is used for separating queries into different batches. The GO keyword is never sent to the database server, and Sql Server wouldn't know what to do with it if it were.

Using table mapping in Entity Framework 6

I'm having lots of difficulty trying to use Entity Framework 6 for a simple application. I used the "EF Designer From Database" option, and something's wrong with my data model or my object model but I can't figure it out. I can't post images yet, but here is the SQL for my data model:
CREATE TABLE [dbo].[Customer](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Company] [varchar](100) NULL,
[Email] [varchar](50) NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Phone] [varchar](20) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED ([ID] ASC)
)
GO
CREATE TABLE [dbo].[Feature](
[ID] [int] NOT NULL,
[Name] [varchar](100) NULL,
[Type] [char](1) NULL,
CONSTRAINT [PK_Feature] PRIMARY KEY CLUSTERED ([ID] ASC)
)
GO
CREATE TABLE [dbo].[License](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Comment] [varchar](max) NULL,
[CustomerID] [int] NULL,
[ExpirationDate] [datetime] NULL,
[SerialNumber] [char](26) NULL,
CONSTRAINT [PK_License] PRIMARY KEY CLUSTERED ([ID] ASC)
)
GO
CREATE TABLE [dbo].[LicenseItem](
[LicenseID] [int] NOT NULL,
[ItemID] [int] NOT NULL,
[Seats] [int] NULL,
CONSTRAINT [PK_LicenseItem] PRIMARY KEY CLUSTERED ([LicenseID] ASC, [ItemID] ASC)
)
GO
CREATE TABLE [dbo].[PackageModule](
[PackageID] [int] NOT NULL,
[ModuleID] [int] NOT NULL,
CONSTRAINT [PK_PackageModule] PRIMARY KEY CLUSTERED ([PackageID] ASC, [ModuleID] ASC)
)
GO
ALTER TABLE [dbo].[License] WITH CHECK ADD CONSTRAINT [FK_License_Customer] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[Customer] ([ID])
GO
ALTER TABLE [dbo].[License] CHECK CONSTRAINT [FK_License_Customer]
GO
ALTER TABLE [dbo].[LicenseItem] WITH CHECK ADD CONSTRAINT [FK_LicenseItem_Feature] FOREIGN KEY([ItemID])
REFERENCES [dbo].[Feature] ([ID])
GO
ALTER TABLE [dbo].[LicenseItem] CHECK CONSTRAINT [FK_LicenseItem_Feature]
GO
ALTER TABLE [dbo].[LicenseItem] WITH CHECK ADD CONSTRAINT [FK_LicenseItem_License] FOREIGN KEY([LicenseID])
REFERENCES [dbo].[License] ([ID])
GO
ALTER TABLE [dbo].[LicenseItem] CHECK CONSTRAINT [FK_LicenseItem_License]
GO
ALTER TABLE [dbo].[PackageModule] WITH CHECK ADD CONSTRAINT [FK_PackageModule_ModuleID_Feature] FOREIGN KEY([ModuleID])
REFERENCES [dbo].[Feature] ([ID])
GO
ALTER TABLE [dbo].[PackageModule] CHECK CONSTRAINT [FK_PackageModule_ModuleID_Feature]
GO
ALTER TABLE [dbo].[PackageModule] WITH CHECK ADD CONSTRAINT [FK_PackageModule_PackageID_Feature] FOREIGN KEY([PackageID])
REFERENCES [dbo].[Feature] ([ID])
GO
ALTER TABLE [dbo].[PackageModule] CHECK CONSTRAINT [FK_PackageModule_PackageID_Feature]
GO
For my object model, I made Feature an abstract class and created Package and Module entities that inherit from Feature (feature is mapped to both Package and Module using Type as a discriminator). Package and Module are associated together with a many-to-many relationship, which is mapped to the PackageModule table, and I associated those to License so that License has Packages and Modules collections (with FK constraints). Here's where I'm stuck:
I added a Seats property to both Package and Module, deleted the auto-generated LicenseItem entity, and mapped LicenseItem to the Package and Module entities to map the Seats property to. This fails because the LicenseID PK is not mapped, and I just can't figure out how to get around this. I'm obviously missing something fundamental, so...be gentle. :)

Categories

Resources