Soldato
So I have been mucking about with the CU tutorial and am now attempting to mimic the CourseAssignment step using a dB generated primary key for the CourseID value instead of user defined one.
So in my example,
Student=Applications
Course=IndApp (individual applications)
CourseAssignment=AppAssignments
In effect; Applications is the solution name, where IndApp contains separate vendor applications presented to the solution.
However; when I attempt to seed the database it throws a wobbly. The error may appear pretty self-explanatory but I'm at a loss where to start.
As far as I can fathom; the AppAssignments table is created correctly and my classes are set correctly. Any pointers would be most welcome.
Cheers, Paul.
So in my example,
Student=Applications
Course=IndApp (individual applications)
CourseAssignment=AppAssignments
In effect; Applications is the solution name, where IndApp contains separate vendor applications presented to the solution.
However; when I attempt to seed the database it throws a wobbly. The error may appear pretty self-explanatory but I'm at a loss where to start.
As far as I can fathom; the AppAssignments table is created correctly and my classes are set correctly. Any pointers would be most welcome.
Code:
SELECT [t].[ID] FROM [Application] t
INNER JOIN @inserted0 i ON ([t].[ID] = [i].[ID])
ORDER BY [i].[_Position];
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (8ms) [Parameters=[@p0='?' (Size = 50), @p1='?' (Size = 50)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [IndApp] ([Application], [Version])
VALUES (@p0, @p1);
SELECT [ID]
FROM [IndApp]
WHERE @@ROWCOUNT = 1 AND [ID] = scope_identity();
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (1ms) [Parameters=[@p0='?' (Size = 50), @p1='?' (Size = 50)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [IndApp] ([Application], [Version])
VALUES (@p0, @p1);
SELECT [ID]
FROM [IndApp]
WHERE @@ROWCOUNT = 1 AND [ID] = scope_identity();
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (0ms) [Parameters=[@p0='?' (Size = 50), @p1='?' (Size = 50)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [IndApp] ([Application], [Version])
VALUES (@p0, @p1);
SELECT [ID]
FROM [IndApp]
WHERE @@ROWCOUNT = 1 AND [ID] = scope_identity();
Exception thrown: 'System.InvalidOperationException' in Microsoft.EntityFrameworkCore.dll
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.3\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.3\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.3\System.Text.Encoding.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Tracker.Program:Error: An error occurred while seeding the database.
System.InvalidOperationException: The instance of entity type 'AppAssignment' cannot be tracked because another instance with the same key value for {'IndAppID', 'ApplicationID'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
.......
Code:
CREATE TABLE [dbo].[AppAssignment] (
[ApplicationID] INT NOT NULL,
[IndAppID] INT NOT NULL,
CONSTRAINT [PK_AppAssignment] PRIMARY KEY CLUSTERED ([IndAppID] ASC, [ApplicationID] ASC),
CONSTRAINT [FK_AppAssignment_Application_ApplicationID] FOREIGN KEY ([ApplicationID]) REFERENCES [dbo].[Application] ([ID]) ON DELETE CASCADE,
CONSTRAINT [FK_AppAssignment_IndApp_IndAppID] FOREIGN KEY ([IndAppID]) REFERENCES [dbo].[IndApp] ([ID]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_AppAssignment_ApplicationID]
ON [dbo].[AppAssignment]([ApplicationID] ASC);
Code:
using Tracker.Models;
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Tracker.Data
{
public static class DbInitializer
{
public static void Initialize(TrackerContext context)
{
//context.Database.EnsureCreated();
// Look for any students.
if (context.Applications.Any())
{
return; // DB has been seeded
}
var Applications = new Application[]
{
new Application{CTXApp="FirstApp",FirstMidName="Carson",LastName="Alexander",BusinessUnit="GMS",EnrollmentDate=DateTime.Parse("2005-09-01")},
new Application{CTXApp="GCMS",FirstMidName="Meredith",LastName="Alonso",BusinessUnit="GMS",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Application{CTXApp="Oracle",FirstMidName="Arturo",LastName="Anand",BusinessUnit="GMS",EnrollmentDate=DateTime.Parse("2003-09-01")},
new Application{CTXApp="Empower",FirstMidName="Gytis",LastName="Barzdukas",BusinessUnit="GMS",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Application{CTXApp="TCSDesktop",FirstMidName="Yan",LastName="Li",BusinessUnit="GMS",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Application{CTXApp="Documentum",FirstMidName="Peggy",LastName="Justice",BusinessUnit="GMS",EnrollmentDate=DateTime.Parse("2001-09-01")},
new Application{CTXApp="OneCDS",FirstMidName="Laura",LastName="Norman",BusinessUnit="GMS",EnrollmentDate=DateTime.Parse("2003-09-01")},
new Application{CTXApp="Access",FirstMidName="Nino",LastName="Olivetto",BusinessUnit="GMS",EnrollmentDate=DateTime.Parse("2005-09-01")}
};
foreach (Application a in Applications)
{
context.Applications.Add(a);
}
context.SaveChanges();
/*var IndApps = new IndApp[]
{
new IndApp{IndAppID=1050,Title="Chemistry",Credits=3},
new IndApp{IndAppID=4022,Title="Microeconomics",Credits=3},
new IndApp{IndAppID=4041,Title="Macroeconomics",Credits=3},
new IndApp{IndAppID=1045,Title="Calculus",Credits=4},
new IndApp{IndAppID=3141,Title="Trigonometry",Credits=4},
new IndApp{IndAppID=2021,Title="Composition",Credits=3},
new IndApp{IndAppID=2042,Title="Literature",Credits=4}
};
foreach (IndApp ia in IndApps)
{
context.IndApps.Add(ia);
}
context.SaveChanges();*/
var IndApps = new IndApp[]
{
new IndApp{Application="Access",Version="1"},
new IndApp{Application="Excel",Version="2"},
new IndApp{Application="Word",Version="3"}
};
foreach (IndApp ia in IndApps)
{
context.IndApps.Add(ia);
}
context.SaveChanges();
var AppAssignments = new AppAssignment[]
{
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Access" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "FirstApp").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Excel" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "GCMS").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Excel" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "FirstApp").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Word" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "FirstApp").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Word" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "Oracle").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Word" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "Empower").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Excel" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "TCSDesktop").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Word" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "Documentum").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Access" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "OneCDS").ID
},
new AppAssignment {
IndAppID = IndApps.Single(ia => ia.Application == "Word" ).ID,
ApplicationID = Applications.Single(a => a.CTXApp == "Empower").ID
}
};
foreach (AppAssignment aa in AppAssignments)
{
context.AppAssignments.Add(aa);
}
context.SaveChanges();
/*
var enrollments = new Enrollment[]
{
new Enrollment{ApplicationID=1,IndAppID=1050,Grade=Grade.A},
new Enrollment{ApplicationID=1,IndAppID=4022,Grade=Grade.C},
new Enrollment{ApplicationID=1,IndAppID=4041,Grade=Grade.B},
new Enrollment{ApplicationID=2,IndAppID=1045,Grade=Grade.B},
new Enrollment{ApplicationID=2,IndAppID=3141,Grade=Grade.F},
new Enrollment{ApplicationID=2,IndAppID=2021,Grade=Grade.F},
new Enrollment{ApplicationID=3,IndAppID=1050},
new Enrollment{ApplicationID=4,IndAppID=1050},
new Enrollment{ApplicationID=4,IndAppID=4022,Grade=Grade.F},
new Enrollment{ApplicationID=5,IndAppID=4041,Grade=Grade.C},
new Enrollment{ApplicationID=6,IndAppID=1045},
new Enrollment{ApplicationID=7,IndAppID=3141,Grade=Grade.A}
};
foreach (Enrollment e in enrollments)
{
context.Enrollments.Add(e);
}
context.SaveChanges(); */
}
}
}
Code:
using Tracker.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
namespace Tracker.Data
{
public class TrackerContext : DbContext
{
public TrackerContext(DbContextOptions<TrackerContext> options) : base(options)
{
}
public DbSet<IndApp> IndApps { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Application> Applications { get; set; }
public DbSet<AppAssignment> AppAssignments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IndApp>().ToTable("IndApp");
//modelBuilder.Entity<IndApp>().ToTable("IndApp2");
modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
modelBuilder.Entity<Application>().ToTable("Application");
modelBuilder.Entity<AppAssignment>().ToTable("AppAssignment");
modelBuilder.Entity<AppAssignment>()
.HasKey(c => new { c.IndAppID, c.ApplicationID });
}
}
}
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Tracker.Models
{
public class Application
{
public int ID { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
[Display(Name = "Citrix Application")]
public string CTXApp { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1)]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
[Column("FirstName")]
[Display(Name = "First Name")]
public string FirstMidName { get; set; }
[Required]
[StringLength(3, MinimumLength = 1)]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
[Display(Name = "Business Unit")]
public string BusinessUnit { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get
{
return LastName + ", " + FirstMidName;
}
}
public ICollection<AppAssignment> AppAssignments { get; set; }
}
}
Code:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Tracker.Models
{
public class IndApp
{
public int ID { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
[Display(Name = "Application")]
public string Application { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
[Display(Name = "Version")]
public string Version { get; set; }
public ICollection<AppAssignment> AppAssignments { get; set; }
}
}
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Tracker.Models
{
public class AppAssignment
{
public int ApplicationID { get; set; }
public int IndAppID { get; set; }
public Application Application { get; set; }
public IndApp IndApp { get; set; }
}
}