scaffold Many to Many Relation with nullable key - c#

I got a table with 3 one to many relations (one many to many relation and a third one to many relation with extra data), but I want to scaffold some relationships from one side of the many to many relation. I don't want it to be linked to the other side of the many to many relationship, so I was thinking of making that nullable but I (with no surprises) can't do that as it is a primary key for it. But is there a workaround to get a null for one side of the Many- to many relation?
Here is the SQL source:
CREATE TABLE [dbo].[ConnectionPointRoutes] (
[ConnectionPointId] INT NOT NULL,
[RouteId] INT NOT NULL,
[SegmentId] INT NOT NULL,
[Position] INT NOT NULL,
CONSTRAINT [PK_dbo.ConnectionPointRoutes] PRIMARY KEY CLUSTERED ([ConnectionPointId] ASC, [RouteId] ASC, [SegmentId] ASC),
CONSTRAINT [FK_dbo.ConnectionPointRoutes_dbo.ConnectionPoints_ConnectionPointId] FOREIGN KEY ([ConnectionPointId]) REFERENCES [dbo].[ConnectionPoints] ([ConnectionPointId]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.ConnectionPointRoutes_dbo.Routes_RouteId] FOREIGN KEY ([RouteId]) REFERENCES [dbo].[Routes] ([RouteId]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.ConnectionPointRoutes_dbo.Segments_SegmentId] FOREIGN KEY ([SegmentId]) REFERENCES [dbo].[Segments] ([SegmentId]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_ConnectionPointId]
ON [dbo].[ConnectionPointRoutes]([ConnectionPointId] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_RouteId]
ON [dbo].[ConnectionPointRoutes]([RouteId] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_SegmentId]
ON [dbo].[ConnectionPointRoutes]([SegmentId] ASC);
And this is the Model, notice that I made it nullable but the database still puts it down as a Not nullable item
namespace InBuildingNavigator.Data.Models
{
public class ConnectionPointRoute
{
public int ConnectionPointId { get; set; }
public int? RouteId { get; set; }
public int? SegmentId { get; set; }
public int Position { get; set; }
public ConnectionPoint ConnectionPoint { get; set; }
public Route Route { get; set; }
public Segment Segment { get; set; }
}
}
Any thoughts on workarounds for this problem?

The problem got solved here: Optional One to many relationship
the connectionpointroute modelbuilder had to be like this :
modelBuilder.Entity<ConnectionPointRoute>()
.HasKey(c => new {c.ConnectionPointId, c.RouteId});

Related

Entity Framework - DB first foreign key table won't show as model

I have created a table with two primary keys and two foreign keys, both foreign keys refer to the same column in the base table - script as follows:
CREATE TABLE [dbo].[TG_PitzulHafrashotShliliVsShotef](
[PitzulHafrashotIdShlili] [int] NOT NULL,
[PitzulHafrashotIdShotef] [int] NOT NULL,
[TaarichIdkun] [datetime2](7) NULL,
PRIMARY KEY CLUSTERED
(
[PitzulHafrashotIdShlili] ASC,
[PitzulHafrashotIdShotef] 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
ALTER TABLE [dbo].[TG_PitzulHafrashotShliliVsShotef] WITH CHECK ADD CONSTRAINT [FK_TG_PitzulHafrashotShliliVsShotef_TG_PitzulHafrashot] FOREIGN KEY([PitzulHafrashotIdShlili])
REFERENCES [dbo].[TG_PitzulHafrashot] ([Id])
GO
ALTER TABLE [dbo].[TG_PitzulHafrashotShliliVsShotef] CHECK CONSTRAINT [FK_TG_PitzulHafrashotShliliVsShotef_TG_PitzulHafrashot]
GO
ALTER TABLE [dbo].[TG_PitzulHafrashotShliliVsShotef] WITH CHECK ADD CONSTRAINT [FK_TG_PitzulHafrashotShliliVsShotef_TG_PitzulHafrashot1] FOREIGN KEY([PitzulHafrashotIdShotef])
REFERENCES [dbo].[TG_PitzulHafrashot] ([Id])
GO
ALTER TABLE [dbo].[TG_PitzulHafrashotShliliVsShotef] CHECK CONSTRAINT [FK_TG_PitzulHafrashotShliliVsShotef_TG_PitzulHafrashot1]
GO
I have then went to my code and updated my model from the DB, added the new table and expected to see a new generated model of the new table.
However, the new model did not generate and my base model looked like that:
public partial class TG_PitzulHafrashot
{
public TG_PitzulHafrashot()
{
this.TG_PitzulHafrashot1 = new HashSet<TG_PitzulHafrashot>();
this.TG_PitzulHafrashot2 = new HashSet<TG_PitzulHafrashot>();
}
/* unrelated properties
*/
public virtual ICollection<TG_PitzulHafrashot> TG_PitzulHafrashot1 { get; set; }
public virtual ICollection<TG_PitzulHafrashot> TG_PitzulHafrashot2{ get; set; }
}
I then deleted the FK constraint from the new table and updated the model again.
After I updated the model. Now, the new class was generated as expected, with no constraints on the base model:
public partial class TG_PitzulHafrashotShliliVsShotef
{
public int PitzulHafrashotIdShlili { get; set; }
public int PitzulHafrashotIdShotef { get; set; }
public Nullable<System.DateTime> TaarichIdkun { get; set; }
public virtual TG_PitzulHafrashot TG_PitzulHafrashot { get; set; }
public virtual TG_PitzulHafrashot TG_PitzulHafrashot1 { get; set; }
}
I then added the FK constraint to the new table and updated the model yet again - The relation created just fine now:
public TG_PitzulHafrashot()
{
this.TG_PitzulHafrashotShliliVsShotef = new HashSet<TG_PitzulHafrashotShliliVsShotef>();
this.TG_PitzulHafrashotShliliVsShotef1 = new HashSet<TG_PitzulHafrashotShliliVsShotef>();
}
/* unrelated properties
*/
public virtual ICollection<TG_PitzulHafrashotShliliVsShotef> TG_PitzulHafrashotShliliVsShotef { get; set; }
public virtual ICollection<TG_PitzulHafrashotShliliVsShotef> TG_PitzulHafrashotShliliVsShotef1 { get; set; }
}
My question is, does entity framework not no how to generate model with and foreign keys properly?
this was a very weird situation as the new table was added to the SqlServer.edmx file however, was not shown in the designer and the corresponding models were never generated, only after I created a table without constraints.
Is there any solution for the foreign key constraint in EF db first?

One-to-one becomes one-to-many Entity Framework generating database-first

I'm generating Entity Framework database first (EF Designer from database). I've got two tables in Microsoft SQL Server:
CREATE TABLE dbo.Person
(
Pk_Person_Id INT IDENTITY PRIMARY KEY,
Name VARCHAR(255),
EmailId VARCHAR(255),
);
CREATE TABLE dbo.PassportDetails
(
Pk_Passport_Id INT PRIMARY KEY,
Passport_Number VARCHAR(255),
Fk_Person_Id INT UNIQUE
FOREIGN KEY REFERENCES dbo.Person(Pk_Person_Id)
);
INSERT INTO dbo.Person
VALUES ('Niraj','v.a#emails.com'),
('Vishwanath','v.v#emails.com'),
('Chetan','c.v#emails.com');
GO
INSERT INTO dbo.PassportDetails
VALUES (101, 'C3031R33', 1), (102, 'VRDK5695', 2), (103, 'A4DEK33D', 3);
GO
SELECT * FROM dbo.Person
SELECT * FROM dbo.PassportDetails;
In SQL Server the relations are shown as one-to-one because Fk_Person_Id is set as isUnique = true:
Fk_Person_Id INT UNIQUE
FOREIGN KEY REFERENCES dbo.Person(Pk_Person_Id));
Now in Visual Studio, I add a new ADO.NET Entity Data Model -> EF Designer from database -> select these two tables and leave all checkbox options by default.
Then after generation is over I see this in Visual Studio diagram .edmx:
And the relationship has changed for one-to-many - why? Is this wrong? I don't want a person to have a collection of passports - it's not the logic I'm trying to describe.
And the EF code:
public partial class Person
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Person()
{
this.PassportDetails = new HashSet<PassportDetail>();
}
public int Pk_Person_Id { get; set; }
public string Name { get; set; }
public string EmailId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PassportDetail> PassportDetails { get; set; }
}
public partial class PassportDetail
{
public int Pk_Passport_Id { get; set; }
public string Passport_Number { get; set; }
public Nullable<int> Fk_Person_Id { get; set; }
public virtual Person Person { get; set; }
}
Context
public partial class LightCRMEntities : DbContext
{
public LightCRMEntities() : base("name=LightCRMEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<PassportDetail> PassportDetails { get; set; }
public virtual DbSet<Person> People { get; set; }
}
Well, in database model editor (.edmx file editor), by clicking on a relationship (arrow between entities daigrams), you can configure its properties in such way, to make it 1-to-1 (it won't change your database!), but then you can generate the code you need to create such database. In result, I got the following:
-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------
-- Creating table 'PassportDetails'
CREATE TABLE [dbo].[PassportDetails] (
[Pk_Passport_Id] int NOT NULL,
[Passport_Number] varchar(255) NULL
);
GO
-- Creating table 'Person'
CREATE TABLE [dbo].[Person] (
[Pk_Person_Id] int IDENTITY(1,1) NOT NULL,
[Name] varchar(255) NULL,
[EmailId] varchar(255) NULL
);
GO
-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------
-- Creating primary key on [Pk_Passport_Id] in table 'PassportDetails'
ALTER TABLE [dbo].[PassportDetails]
ADD CONSTRAINT [PK_PassportDetails]
PRIMARY KEY CLUSTERED ([Pk_Passport_Id] ASC);
GO
-- Creating primary key on [Pk_Person_Id] in table 'Person'
ALTER TABLE [dbo].[Person]
ADD CONSTRAINT [PK_Person]
PRIMARY KEY CLUSTERED ([Pk_Person_Id] ASC);
GO
-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------
-- Creating foreign key on [Pk_Passport_Id] in table 'PassportDetails'
ALTER TABLE [dbo].[PassportDetails]
ADD CONSTRAINT [FK__PassportD__Pk_Pa__5BE2A6F2]
FOREIGN KEY ([Pk_Passport_Id])
REFERENCES [dbo].[Person]
([Pk_Person_Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF when not trying to set a value for an IDENTITY column

I have a WebApi2/Entity Framework project using Code First that is throwing this error:
Cannot insert explicit value for identity column in table 'Sessions' when IDENTITY_INSERT is set to OFF.
This is the model:
public class Session
{
[Key, ForeignKey("Device")]
public long Id { get; set; }
public virtual Device Device { get; set; }
}
public class Device
{
[Key]
public long Id { get; set; }
public long AnalyticsId { get; set; }
[ForeignKey("AnalyticsId")]
public Session AnalyticsSession { get; set; }
}
The controller:
public async Task<IHttpActionResult> PostSession(SessionInitialDTO sessionDTO)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Session session = new Session();
db.Sessions.Add(session);
Analytics.Models.Device device = sessionDTO.Device;
device.AnalyticsSession = session;
db.Devices.Add(device);
await db.SaveChangesAsync();
return CreatedAtRoute("CreateInitialSession", new { id = session.Id }, session);
}
Everything I've read says that this issue comes from trying to set an IDENTITY column to a value, but as far as I can tell, I'm not trying to do that (or at least if I am, am not seeing where). The Device object in the DTO does not set the Id. I've seen some things suggesting using the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] annotation to specify that the field is autogenerated, but this then causes issues because of the ForeignKey
This is the code for the generated tables:
CREATE TABLE [dbo].[Sessions] (
[Id] BIGINT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_dbo.Sessions] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.Sessions_dbo.Devices_Id] FOREIGN KEY ([Id]) REFERENCES [dbo].[Devices] ([Id])
);
CREATE TABLE [dbo].[Devices] (
[Id] BIGINT IDENTITY (1, 1) NOT NULL,
[AnalyticsId] BIGINT NOT NULL,
CONSTRAINT [PK_dbo.Devices] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Bizarrely, this used to work, I made some changes to the model, started getting this, reverted to this version of the model, and the error persisted.
Without trying to understand if the model meets the requirements (a device can have one or zero sessions), you are trying to build a 1-1 relationship so Session.Id cannot be autogenerated (with EF by default integer Keys are autogenerated).
To specify it you can just add attribute [DatabaseGenerated(DatabaseGeneratedOption.None)] to Session.Id property.
After that you need to migrate the database because Session.Id will not be an IDENTITY.
The problem is that Session.Id is identity column. Device record created first and try set Session foreign key - Id.
You must disable identity:
public class Session
{
[Key, ForeignKey("Device")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Id { get; set; }
public virtual Device Device { get; set; }
}

EF6 + Code First + Fluent : Error Cannot insert the value NULL into column 'ID', table 'X' column does not allow nulls

There are tons of questions mentionning this error, I went through each one I found but they didn't correspond to my issue. Most of the time in the questions I found, the problem comes from the fact that the author is willing to manually give an ID to an entity but forgets to the switch the Autogenerated option to off.
My problem is exactly the opposit. I have several tables all containing a ID column which is automatically incremented by the database. The CRUDs operations are working fine on all of them but one.
I'm getting the terrible exception which is mentionned in the Title. I've spent 2 hours on this but I can't figure out why. Everything seems just fine.
Here is my model :
public class House
{
public int ID { get; set; }
public string Name {get;set;}
public DateTime CreationDate { get; set; }
public int CompanyID { get; set; }
public virtual BuildingCompany Assignation { get; set; }
public int? NoteID { get; set; }
public Note Note { get; set; }
public int UserID { get; set; }
public virtual User User { get; set; }
public int? FileID { get; set; }
public virtual File File { get; set; }
}
Here is the mapping code
modelBuilder.Entity<House>().HasKey(r => r.ID);
modelBuilder.Entity<House>().Property(r => r.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<House>().HasRequired(r => r.Company).WithMany(a => a.Houses).HasForeignKey(r => r.CompanyID).WillCascadeOnDelete(false);
modelBuilder.Entity<House>().HasOptional(r => r.File).WithMany().HasForeignKey(r => r.FileID);
modelBuilder.Entity<House>().HasRequired(r => r.User).WithMany().HasForeignKey(r => r.UserID);
modelBuilder.Entity<House>().HasOptional(r => r.Note).WithRequired(n => n.House);
And here is the code I use to try to persist an entity (add a row) :
House house = new House
{
ID=0, // I also tried to remove this line
Name="Nice House",
CompanyID= // Some Integer,
CreationDate=DateTime.Now,
UserID= // Some Integer
};
context.Houses.Add(house)
context.Save();
This makes no sense to me, I've tried to debug and when my code hits the Save Method of my context, the Local cache contains the entity that I've created with the right parameters but then it throws me this error :
Error Cannot insert the value NULL into column 'ID', table 'Houses' column does not allow nulls.
Just as a reminder, I don't need/want to set the ID myself. I'm expecting that EF does it for me as it does with my other tables. That's why this problem particularly puzzles me.
Thanks for your help
Edit
Here is the Database Schema. The Database is auto-generated by EF. I only do Automatic Migrations after every model change. I don't touch at this level of detail.
CREATE TABLE [dbo].[Houses] (
[ID] INT NOT NULL,
[Name] NVARCHAR (MAX) NULL,
[CreationDate] DATETIME NOT NULL,
[CompanyID] INT NOT NULL,
[NoteID] INT NULL,
[UserID] INT NOT NULL,
[FileID] INT NULL,
CONSTRAINT [PK_dbo.Houses] PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_dbo.Houses_dbo.Files_FileID] FOREIGN KEY ([FileID]) REFERENCES [dbo].[Files] ([ID]),
CONSTRAINT [FK_dbo.Houses_dbo.Users_UserID] FOREIGN KEY ([UserID]) REFERENCES [dbo].[Users] ([ID]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Houses_dbo.BuildingCompanies_CompaniesID] FOREIGN KEY ([CompanyID]) REFERENCES [dbo].[BuildingCompanies] ([ID])
);
GO
CREATE NONCLUSTERED INDEX [IX_CompanyID]
ON [dbo].[Houses]([CompanyID] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_UserID]
ON [dbo].[Houses]([UserID] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_FileID]
ON [dbo].[Houses]([FileID] ASC);
how is your database crearted ? are you sure the column is set to identity on the server ?
if not try to drop the database and re-run your app.

A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column:

First, thanks for taking the time to read this. I'm having some difficulties with trying to update a database using EF. I've used this same approach before on another project, so I'm thinking the issue is perhaps in the database, but I'm just not seeing it. The database is a legacy db in SQL 2005, and the naming convention has a lot to be desired, therefore I've been mapping the inconsistent names to something more consistent via the HasColumnName method: as in.
modelBuilder.Entity<Case_Person_1>().ToTable("dbo.Case_Person_1");
modelBuilder.Entity<Case_Person_1>().Property(c => c.Id).HasColumnName("CaseNumber");
I've compared my issue to the other similar ones and investigated to verify the foreign key relationships are pointed in the right direction and that the identity is only on the PK. When I do NOT have Data Generation Option explicitly set, the command fires against the database, but it fails b/c I'm inserting a 0 as my Key and option explicit is set to OFF. I can see this in SQL Profiler. When I add the option for Identity, I get the Referential constraint error.
I've lost 2 days on this and am no closer to reaching a solution and I'm pretty much at the end of my rope. As an aside, in my other project I didn't need to decorate my POCO's with the DatabaseGeneratedOption, yet I didn't get any error on inserts. I didn't know if this was a SQL 2005 thing, or if I'm missing something else...
the full error detail is here:
System.Data.Entity.Infrastructure.DbUpdateException was caught
Message=An error occurred while updating the entries. See the inner
exception for details. Source=EntityFramework StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Scyfis.Ocyf.DataLayer.EntityExtensions.AddItem[T](T entity, DbSet1 dbSet, DbContext context, Action2 foriegnKeyUpdater) in
C:\TFS\CGProjects\GOC\SCYFIS\PHTSY\Dev\src\Datalayer\Helpers\EntityExtensions.cs:line
83
at Scyfis.Ocyf.DataLayer.EntityExtensions.SaveItem[T](T entity, DbSet1 dbSet, DbContext context, Action2 foriegnKeyUpdater) in
C:\TFS\CGProjects\GOC\SCYFIS\PHTSY\Dev\src\Datalayer\Helpers\EntityExtensions.cs:line
27
at Scyfis.Ocyf.DataLayer.Case_PHTSYRepository.Save(Case_PHTSY model) in
C:\TFS\CGProjects\GOC\SCYFIS\PHTSY\Dev\src\Datalayer\Custom\Case_PHTSYRepository.cs:line
44
at Scyfis.Ocyf.Service.Case_PHTSYService.Create(Case_PHTSY model) in
C:\TFS\CGProjects\GOC\SCYFIS\PHTSY\Dev\src\Service\Custom\Case_PHTSYService.cs:line
184 InnerException: System.Data.UpdateException
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
StackTrace:
at System.Data.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode
changeNode, UpdateCompiler compiler)
at System.Data.Mapping.Update.Internal.UpdateTranslator.d_0.MoveNext()
at System.Linq.Enumerable.d_711.MoveNext()
at System.Data.Mapping.Update.Internal.UpdateCommandOrderer..ctor(IEnumerable1
commands, UpdateTranslator translator)
at System.Data.Mapping.Update.Internal.UpdateTranslator.ProduceCommands()
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager
stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager
entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.InvalidOperationException
Message=A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
Source=System.Data.Entity
StackTrace:
at System.Data.Mapping.Update.Internal.UpdateCompiler.BuildSetClauses(DbExpressionBinding
target, PropagatorResult row, PropagatorResult originalRow,
TableChangeProcessor processor, Boolean insertMode, Dictionary`2&
outputIdentifiers, DbExpression& returning, Boolean& rowMustBeTouched)
at System.Data.Mapping.Update.Internal.UpdateCompiler.BuildInsertCommand(PropagatorResult
newRow, TableChangeProcessor processor)
at System.Data.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode
changeNode, UpdateCompiler compiler)
InnerException:
public partial class Case_PHTSY
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? FamilyHistoryID { get; set; }
public int? PersonId { get; set; }
public DateTime? ReportDate { get; set; }
public string PhysicianName { get; set; }
public string MRNumber { get; set; }
public virtual F_FamilyHistory F_FamilyHistory { get; set; }
public virtual Person Person { get; set; }
public virtual ICollection<CP_ActualDischarge> CP_ActualDischarges { get; set; }
public virtual ICollection<CP_Barrier> Barriers { get; set; }
public virtual ICollection<CP_AgencyContact> AgencyContacts { get; set; }
public virtual ICollection<CP_DischargeActivity> DischargeActivities { get; set; }
public virtual ICollection<C_Role> Roles { get; set; }
public virtual ICollection<Case_Person_RD1> Case_Person_RD1s { get; set; }
public virtual ICollection<PHTSY_CensusCode> PHTSY_CensusCodes { get; set; }
}
public class CP_ActualDischarge
{
public int Id { get; set; }
[ForeignKey("Case_PHTSY")]
public int Case_PHTSYId{ get; set; }
...
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
public partial class CP_Barrier
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Case_PHTSYId { get; set; }
...
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
public partial class CP_AgencyContact
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int Case_PHTSYId { get; set; }
...
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
public partial class CP_DischargeActivity
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Case_PHTSYId { get; set; }
...
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
public partial class C_Role
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Case_PHTSYId{ get; set; }
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
}
public partial class Case_Person_RD1
{
public virtual C_Role C_Role { get; set; }
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
The foreign keys:
ALTER TABLE [dbo].[CP_ActualDischarge] WITH NOCHECK ADD CONSTRAINT [FK_CP_ActualDischarge_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_ActualDischarge] CHECK CONSTRAINT [FK_CP_ActualDischarge_Case_PHTSY]
ALTER TABLE [dbo].[CP_AgencyContacts] WITH NOCHECK ADD CONSTRAINT [FK_CP_AgencyContacts_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_AgencyContacts] CHECK CONSTRAINT [FK_CP_AgencyContacts_Case_PHTSY]
ALTER TABLE [dbo].[CP_Barriers] WITH NOCHECK ADD CONSTRAINT [FK_CP_Barriers_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_Barriers] CHECK CONSTRAINT [FK_CP_Barriers_Case_PHTSY]
ALTER TABLE [dbo].[CP_DischargeActivities] WITH NOCHECK ADD CONSTRAINT [FK_CP_DischargeActivities_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_DischargeActivities] CHECK CONSTRAINT [FK_CP_DischargeActivities_Case_PHTSY]
GO
modelBuilder.Entity<Case_PHTSY>().HasMany(c => c.AgencyContacts).WithOptional().HasForeignKey(k => k.Case_PHTSYId);
modelBuilder.Entity<Case_PHTSY>().HasMany(c => c.Barriers).WithOptional().HasForeignKey(k => k.Case_PHTSYId);
modelBuilder.Entity<Case_PHTSY>().HasMany(r => r.DischargeActivities).WithOptional().HasForeignKey(k => k.Case_PhstsyId);
modelBuilder.Entity<Case_PHTSY>().HasMany(c => c.Roles).WithOptional().HasForeignKey(k => k.Case_PHTSYId);
modelBuilder.Entity<Case_PHTSY>().HasMany(m => m.Case_Person_RD1s).WithOptional().HasForeignKey(k => k.Case_PhtsyId);
modelBuilder.Entity<Case_PHTSY>().HasMany(o => o.DischargeActivities).WithOptional().HasForeignKey(k => k.Case_PhstsyId);
modelBuilder.Entity<Case_PHTSY>().HasOptional(o => o.F_FamilyHistory).WithRequired();
modelBuilder.Entity<Case_PHTSY>().HasMany(o => o.PHTSY_CensusCodes).WithOptional().HasForeignKey(k => k.Case_PHTSYId);
the primary table:
CREATE TABLE [dbo].[Case_PHTSY](
[Id] [int] IDENTITY(5000,1) NOT FOR REPLICATION NOT NULL,
[FamilyHistoryID] [int] NULL,
[IntensityNHours] [smallint] NULL,
[IEPRequested] [bit] NULL CONSTRAINT [DF_Case_PHTSY_IEPRequested] DEFAULT (0),
...
[Kidnet] [bit] NULL,
CONSTRAINT [PK_Case_PHTSY] 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]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Case_PHTSY] WITH NOCHECK ADD CONSTRAINT [FK_Case_PHTSY_F_FamilyHistory] FOREIGN KEY([FamilyHistoryID])
REFERENCES [dbo].[F_FamilyHistory] ([FamilyHistoryID])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[Case_PHTSY] CHECK CONSTRAINT [FK_Case_PHTSY_F_FamilyHistory]
GO
ALTER TABLE [dbo].[Case_PHTSY] WITH CHECK ADD CONSTRAINT [FK_Case_PHTSY_Persons] FOREIGN KEY([CaseChildID])
REFERENCES [dbo].[Persons] ([PersonID])
GO
ALTER TABLE [dbo].[Case_PHTSY] CHECK CONSTRAINT [FK_Case_PHTSY_Persons]
CREATE TABLE [dbo].[CP_ActualDischarge](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Case_PHTSYId] [int] NOT NULL,
[DischargeDate] [datetime] NULL,
CONSTRAINT [PK_CP_ActualDischarge] 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]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[CP_ActualDischarge] WITH NOCHECK ADD CONSTRAINT [FK_CP_ActualDischarge_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_ActualDischarge] CHECK CONSTRAINT [FK_CP_ActualDischarge_Case_PHTSY]
CREATE TABLE [dbo].[CP_AgencyContacts](
[AgencyContactID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[Case_PHTSYId] [int] NOT NULL,
[AgencyType] [int] NULL,
[Agency] [int] NULL,
CONSTRAINT [PK_Case_PHTSY_AgencyContacts] PRIMARY KEY CLUSTERED
(
[AgencyContactID] 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 [dbo].[CP_AgencyContacts] WITH NOCHECK ADD CONSTRAINT [FK_CP_AgencyContacts_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_AgencyContacts] CHECK CONSTRAINT [FK_CP_AgencyContacts_Case_PHTSY]
I had the same error. Eventually traced it to an incorrect relationship. I was linking between two primay keys at the database instead of a primary and a foreign.
It only took about another hour of head banging, but I came to a solution using a hint from another response. The short of it is that EntityFramework was confused about some of the relationships (or my description using fluent expressions was).
I finally bit the bullet and cleaned up some of the names of the columns in the database and made them 'conventional', i.e. tableName+Id removed my fluent expressions and it worked.
I also took out a composite key on one table, added an Id field and made the composite key a unique index instead.
I hope this helps someone else.
I also confirmed my suspicion that when using SQL Server 2008 the identity annotation was not needed. The database being used was 2005.
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
I had to manually remove a bad reference in the .edmx.

Categories