Double foreign key generation - c#

This is a followup-question of this question, where i had a similar problem. But this is solved now by default foreign key convention.
My problem now is (in short), that my migrations generates
int ReferencedEntityID;
int ReferencedEntity_ReferencedEntityID;
where one is an integer property in my model and the other one is a virtual property.
My migrations generates this:
"dbo.Contracts",
c => new
{
ContractId = c.Int(nullable: false, identity: true),
PricePerUnit = c.Double(nullable: false),
Unit = c.Int(nullable: false),
Currency = c.Int(nullable: false),
ClientId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
ArticleId = c.Int(nullable: false),
Client_ClientId = c.Int(),
Article_ArticleId = c.Int(),
})
As you can see, Client & Article are referenced twice.
Here are my models
public class Client {
public Client() { }
[Key]
public int ClientId { get; set; }
public string Number { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Memo { get; set; }
public bool isMerchant { get; set; }
public string Name
{
get
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
public int? MerchantReferenceId { get; set; }
public virtual Client MerchantReference { get; set; }
[Required]
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
public virtual ICollection<Contract> Contracts { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Article {
public Article() { }
[Key]
public int ArticleId { get; set; }
[Required]
public string Code { get; set; }
public string Name { get; set; }
public bool TrackStock { get; set; }
public int CurrentStock { get; set; }
public double? Price { get; set; }
[Required]
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
[Required]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Contract> Contracts { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Contract {
public Contract() { }
[Key]
public int ContractId { get; set; }
public double PricePerUnit { get; set; }
public int Unit { get; set; }
public int Currency { get; set; }
[Required]
public int ClientId { get; set; }
// [ForeignKey("ClientId")]
public virtual Client Client { get; set; }
[Required]
public int CompanyId { get; set; }
//[ForeignKey("CompanyID")]
public virtual Company Company { get; set; }
[Required]
public int ArticleId { get; set; }
// [ForeignKey("ArticleId")]
public virtual Article Article { get; set; }
}
Here is my OnModelCreating()
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// modelBuilder.Entity<Contract>().HasRequired(bm => bm.Company).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<Contract>().HasRequired(bm => bm.Article).WithMany().HasForeignKey(dl => dl.ArticleId).WillCascadeOnDelete(false);//.Map( dl => dl.MapKey("ArticleId"))
modelBuilder.Entity<Contract>().HasRequired(bm => bm.Client).WithMany().HasForeignKey(dl => dl.ClientId).WillCascadeOnDelete(false);//.Map(dl => dl.MapKey("ClientId"))
modelBuilder.Entity<Article>().HasRequired(bm => bm.Company).WithMany().HasForeignKey(dl => dl.CompanyId).WillCascadeOnDelete(false);//.Map(dl => dl.MapKey("CompanyId"))
modelBuilder.Entity<Measurement>().HasRequired(bm => bm.Company).WithMany().HasForeignKey(dl => dl.CompanyId).WillCascadeOnDelete(false); //.Map(dl => dl.MapKey("CompanyId"))
modelBuilder.Entity<Order>().HasRequired(bm => bm.Client).WithMany().HasForeignKey(dl => dl.ClientId).WillCascadeOnDelete(false); //.Map(dl => dl.MapKey("ClientId"))
modelBuilder.Entity<Order>().HasRequired(bm => bm.Article).WithMany().HasForeignKey(dl => dl.ArticleId).WillCascadeOnDelete(false);//.Map(dl => dl.MapKey("ArticleId"))
modelBuilder.Entity<IncomingMeasurement>().HasRequired(bm => bm.client).WithMany().HasForeignKey(dl => dl.ClientId).WillCascadeOnDelete(false);//.Map(dl => dl.MapKey("ClientId"))
modelBuilder.Entity<Client>().HasOptional(c => c.MerchantReference).WithMany().HasForeignKey(dl => dl.MerchantReferenceId); //.Map(dl => dl.MapKey("MerchantReferenceId"))
//Required fields
base.OnModelCreating(modelBuilder);
}
What do i have to do, to create them both:
Required
Both in one property in my db-schema (as it should)

It is OK, even recommended, to have primitive FK properties (like ArticleId) accompanying the "real" references. In EF this is called a foreign key association as opposed to an independent association where there is only a reference (like Article.Company).
So you can keep your model the way it is. You just have to specify the foreign keys.
I tried with a few classes in the model of your previous question and this produced the desired results:
modelBuilder.Entity<Article>().HasMany(a => a.Contracts)
.WithRequired(c => c.Article)
.HasForeignKey(c => c.ArticleID).WillCascadeOnDelete(false);
modelBuilder.Entity<Client>().HasMany(c => c.Contracts)
.WithRequired(c => c.Client)
.HasForeignKey(c => c.ClientID).WillCascadeOnDelete(false);
modelBuilder.Entity<Company>().HasMany(c => c.Articles)
.WithRequired(a => a.Company)
.HasForeignKey(c => c.CompanyID).WillCascadeOnDelete(false);
Note that I turned around the definitions because when I did it your way, but with HasForeignKey it still duplicated the FK fields. I'm not sure why.

Related

Many to many relationship with the the same table. EF

I have a C# running on .NET 5.0 application. And I have the following tables
public class Attribute
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
public List<AssessmentAttributeItem> ItemMappings { get; set; }
public List<AssessmentAttributeItem> AttributeMappings { get; set; }
public Attribute()
{
ItemMappings = new List<AssessmentAttributeItem>();
AttributeMappings = new List<AssessmentAttributeItem>();
}
}
public class AssessmentAttributeItem
{
[Key]
public int Id { get; set; }
[Required]
public int AttributeId { get; set; }
[ForeignKey("AttributeId")]
public virtual Attribute Attribute { get; set; }
public int? ItemId { get; set; }
[ForeignKey("ItemId")]
public virtual AssessmentItem Item { get; set; }
public int? ChildAttributeId { get; set; }
[ForeignKey("ChildAttributeId")]
public virtual Attribute ChildAttribute { get; set; }
}
And I am using Fluent API to specify the relationship like the following
modelBuilder.Entity<AssessmentAttributeItem>()
.HasOne(x => x.Item)
.WithMany().HasForeignKey(y => y.ItemId);
modelBuilder.Entity<AssessmentAttributeItem>()
.HasOne(x => x.Attribute)
.WithMany(y => y.ItemMappings);
modelBuilder.Entity<AssessmentAttributeItem>()
.HasOne(x => x.ChildAttribute)
.WithMany().HasForeignKey(y => y.ChildAttributeId);
Mmy question is: when I try to add migration it is adding an extra column called AttributeId1
migrationBuilder.AddColumn<int>(
name: "AttributeId1",
table: "AssessmentAttributeItems",
type: "int",
nullable: true);
public class AssessmentItem
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[StringLength(50)]
public string Code { get; set; }
}
I want my table to look like this
ID
AttributeId
ItemId
ChildAttributeId
.
.
.
.

EF Core - Unwanted foreign keys being added automatically when I specify my own ones

I appear to have duplicate foreign keys in my GroceryItemGroceryStores many to many join table: VeganItemId, VeganItemsId, EstablishmentId, EstablishmentsId.
I'm only actually using VeganItemId and EstablishmentId and they are the only ones being added to. It is adding VeganItemsId and EstablishmentsId columns to my table automatically. How do I tell it not to?:
This image of my database shows the foreign keys in effect:
My DatabaseContext:
modelBuilder.Entity<GroceryItem>(gi =>
{
gi.HasIndex(e => new { e.Brand, e.Name }).IsUnique();
gi.HasKey(e => e.Id);
gi.Property(e => e.Tags)
.HasConversion(
v => JsonSerializer.Serialize(v, null),
v => JsonSerializer.Deserialize<List<GroceryItemTag>>(v, null),
new ValueComparer<IList<GroceryItemTag>>(
(c1, c2) => c1.SequenceEqual(c2),
c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
c => (IList<GroceryItemTag>)c.ToList()));
});
modelBuilder.Entity<GroceryStore>(gs =>
{
gs.HasIndex(gs => gs.PlaceId).IsUnique();
gs.HasMany(gs => gs.VeganItems)
.WithMany(vi => vi.Establishments)
.UsingEntity<GroceryItemGroceryStore>
(gigs => gigs.HasOne<GroceryItem>().WithMany(),
gigs => gigs.HasOne<GroceryStore>().WithMany());
});
modelBuilder.Entity<GroceryItemGroceryStore>(gigs =>
{
gigs.HasIndex(e => new { e.VeganItemId, e.EstablishmentId }).IsUnique();
gigs.HasKey(e => new { e.VeganItemId, e.EstablishmentId });
});
public DbSet<GroceryItem> GroceryItems { get; set; }
public DbSet<GroceryItemGroceryStore> GroceryItemGroceryStores { get; set; }
public DbSet<GroceryStore> GroceryStores { get; set; }
My tables:
public class GroceryStore
{
[Key]
public Int64 Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string PlaceId { get; set; }
[Required]
public string Street { get; set; }
public string Suburb { get; set; }
public string City { get; set; }
public string StreetNumber { get; set; }
public virtual ICollection<GroceryItem> VeganItems { get; set; }
}
public class GroceryItem
{
[Key]
public Int64 Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Image { get; set; }
[Required]
public int IsNotVeganCount { get; set; }
[Required]
public int IsVeganCount { get; set; }
[Required]
public int RatingsCount { get; set; }
[Required]
public int Rating { get; set; }
[Required]
public List<GroceryItemTag> Tags { get; set; }
[Required]
public int CurrentRevisionId { get; set; }
public virtual ICollection<GroceryStore> Establishments { get; set; }
}
public class GroceryItemGroceryStore
{
[Key]
public Int64 Id { get; set; }
[Key, Column(Order = 0), Required]
public int VeganItemId { get; set; }
[Key, Column(Order = 1), Required]
public int EstablishmentId { get; set; }
public virtual GroceryItem VeganItem { get; set; }
public virtual GroceryStore Establishment { get; set; }
[Required]
public int NotInEstablishmentCount { get; set; }
[Required]
public int InEstablishmentCount { get; set; }
[Required]
public double Price { get; set; }
}
Even adding .HasForeignKey(o => o.VeganItemId) like so:
modelBuilder.Entity<GroceryStore>(gs =>
{
gs.HasIndex(gs => gs.PlaceId).IsUnique();
gs.HasMany(gs => gs.VeganItems)
.WithMany(vi => vi.Establishments)
.UsingEntity<GroceryItemGroceryStore>
(gigs => gigs.HasOne<GroceryItem>().WithMany().HasForeignKey(o => o.EstablishmentId),
gigs => gigs.HasOne<GroceryStore>().WithMany().HasForeignKey(o => o.VeganItemId));
});
Makes the table have VeganItemId1 and EstablishmentId1:
EDIT: I have since tried deleting all occurrences of VeganItemsId and EstablishmentsId from all migration files but when inserting to the database it still thinks it needs to insert EstablishmentsId.
In GroceryItemGroceryStore change the type of VeganItemId and EstablishmentId to Int64 so that they match the type of the corresponding primary keys in GroceryItem and GroceryStore -
[Column(Order = 0), Required]
public Int64 VeganItemId { get; set; } // Key attribute is not needed here
[Column(Order = 1), Required]
public Int64 EstablishmentId { get; set; } // Key attribute is not needed here
Modify the configuration for GroceryStore to include the navigation properties and to explicitly configure the foreign keys -
builder.Entity<GroceryStore>(gs =>
{
gs.HasIndex(gs => gs.PlaceId).IsUnique();
gs.HasMany(gs => gs.VeganItems)
.WithMany(vi => vi.Establishments)
.UsingEntity<GroceryItemGroceryStore>
(gigs => gigs.HasOne(p => p.VeganItem)
.WithMany().HasForeignKey(p => p.VeganItemId),
gigs => gigs.HasOne(p => p.Establishment)
.WithMany().HasForeignKey(p => p.EstablishmentId));
});
That should fix the duplicate keys issue.
Also, you should remove the following property from GroceryItemGroceryStore -
[Key]
public Int64 Id { get; set; }
since you are configuring a composite primary key through fluent API.
The presence of such FKs is a clear indication of relationship misconfiguration and usually happens when you leave out from the fluent configuration some of the relationship navigation properties, in which case EF maps them to a separate FK relationship with conventional FK property/column names.
In this particular case, the misconfiguration is here
gigs => gigs.HasOne<GroceryItem>().WithMany() // (1)
and
gigs.HasOne<GroceryStore>().WithMany() // (2)
because you have left out the navigation properties of GroceryItemGroceryStore
public virtual GroceryItem VeganItem { get; set; } // (1)
public virtual GroceryStore Establishment { get; set; } // (2)
May be they wasn't there initially and you have added them later. But you should always keep the fluent configuration in sync with the model, which in this case of course should be something like
gigs => gigs.HasOne(e => e.VeganItem).WithMany()
and
gigs.HasOne(e => e.Establishment).WithMany()
Your issue is that you have defined VeganItemId and EstablishmentId as part of athe composite Primary Key of GroceryItemGroceryStore, in conjunction with the Artificitial key of Id
It is not necessary and even counter productive to define a composite key that includes a column that is already unique for all rows in the table, if there is a single column that is unique for all records, and you were going to include it in the primary key, then you should just use that column as the PK.
Your fluent configuration is conflicting with your attribute configuration, I would suggest the following is at least part of the solution:
public class GroceryItemGroceryStore
{
[Key]
public Int64 Id { get; set; }
[ForeignKey(nameof(VeganItem)), Column(Order = 0), Required]
public int VeganItemId { get; set; }
[ForeignKey(nameof(Establishment)), Column(Order = 1), Required]
public int EstablishmentId { get; set; }
public virtual GroceryItem VeganItem { get; set; }
public virtual GroceryStore Establishment { get; set; }
[Required]
public int NotInEstablishmentCount { get; set; }
[Required]
public int InEstablishmentCount { get; set; }
[Required]
public double Price { get; set; }
}

Error seeding table data using EF Core MVC

I am new to MVC and EF Core and have been trying to seed some data. All my tables seed correctly except for one table and I am tired of banging my head against a wall. I have even recreated the entire application with no luck. I am certain I am missing something obvious.
My Models
public class AgreementType
{
public int AgreementTypeID { get; set; }
[Required]
[StringLength(100)]
public string Description { get; set; }
[DisplayName("Creation Date")]
public DateTime CreationDate { get; set; }
[StringLength(100)]
[DisplayName("Created By")]
public string CreatedBy { get; set; }
public Agreement Agreement { get; set; }
}
public class ContactType
{
public int ContactTypeID { get; set; }
[Required]
[StringLength(100)]
public string Description { get; set; }
[DisplayName("Creation Date")]
public DateTime CreationDate { get; set; }
[StringLength(100)]
[DisplayName("Created By")]
public string CreatedBy { get; set; }
public Contact Contact { get; set; }
}
public class Branch
{
public int BranchID { get; set; }
public string Name { get; set; }
[DisplayName("Creation Date")]
public DateTime CreationDate { get; set; }
[StringLength(100)]
[DisplayName("Created By")]
public string CreatedBy { get; set; }
public int IntermediaryID { get; set; }
public Intermediary Intermediary { get; set; }
public int RegionID { get; set; }
public virtual Region Region { get; set; }
}
My Context Class
public class BizDevHubContext : DbContext
{
public BizDevHubContext(DbContextOptions<BizDevHubContext> options) : base(options)
{
}
public DbSet<AgreementType> AgreementType { get; set; }
public DbSet<Branch> Branch { get; set; }
public DbSet<ContactType> ContactTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AgreementType>().ToTable("AgreementType");
modelBuilder.Entity<Branch>().ToTable("Branch");
modelBuilder.Entity<ContactType>().ToTable("ContactType");
// One to One
modelBuilder.Entity<Agreement>()
.HasOne(b => b.AgreementType)
.WithOne(i => i.Agreement)
.HasForeignKey<Agreement>(b => b.AgreementTypeID);
modelBuilder.Entity<Contact>()
.HasOne(b => b.ContactType)
.WithOne(i => i.Contact)
.HasForeignKey<Contact>(b => b.ContactTypeID);
//One to Many
modelBuilder.Entity<Region>()
.HasMany(c => c.Branch)
.WithOne(e => e.Region)
.HasForeignKey((p => p.BranchID));
// Set default dates
modelBuilder.Entity<AgreementType>()
.Property(b => b.CreationDate)
.HasDefaultValueSql("getdate()");
modelBuilder.Entity<Branch>()
.Property(b => b.CreationDate)
.HasDefaultValueSql("getdate()");
modelBuilder.Entity<ContactType>()
.Property(b => b.CreationDate)
.HasDefaultValueSql("getdate()");
}
}
My Initializer Class
if (context.Branch.Any())
{
return;
}
var branches = new Branch[]
{
new Branch{Name="Bloemfontein",CreationDate=DateTime.Now,CreatedBy="System"},
new Branch{Name="Cape Town",CreationDate=DateTime.Now,CreatedBy="System"},
new Branch{Name="Durban",CreationDate=DateTime.Now,CreatedBy="System"},
new Branch{Name="Nelspruit",CreationDate=DateTime.Now,CreatedBy="System"},
new Branch{Name="Johannesburg",CreationDate=DateTime.Now,CreatedBy="System"},
new Branch{Name="Port Shepstone",CreationDate=DateTime.Now,CreatedBy="System"},
new Branch{Name="Pretoria",CreationDate=DateTime.Now,CreatedBy="System"}
};
foreach (Branch b in branches)
{
context.Branch.Add(b);
}
context.SaveChanges();
The other tables all seed except the Branch table.
Please help!

Cannot create the foreign key "FK_ApplicationInfos_UserProfiles_UserProfileId" with the SET NULL referential action

How fix the problem ?
Error Message
In Entity Framework Core, I'm attempting to create a system with 4 Db Models - User,UserProfile,Review, ApplicationInfo.
I tried a lot of things, well, I don’t understand the concept of how to fix the situation, I clearly gave cascade in modelOnCreate
Model User.
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Token { get; set; }
public UserProfile UserProfile { get; set; }
}
Model UserProfile
public class UserProfile
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public IEnumerable<ApplicationInfo> ApplicationInfos { get; set; }
public IEnumerable<Review> Reviews { get; set; }
}
Model Review
public class Review
{
public int Id { get; set; }
public string Text { get; set; }
public string ImageLocation { get; set; }
public string Version { get; set; }
public string Rate { get; set; }
//One(AppInfo) to Many(Review)
public int ApplicationInfoId { get; set; }
public ApplicationInfo ApplicationInfo { get; set; }
//One(UserProfile) to Many(Review)
public int UserProfileId { get; set; }
[Required]
public UserProfile UserProfile { get; set; }
}
Model ApplicationInfo
public class ApplicationInfo
{
[Key]
public int Id { get; set; }
[Required]
public string ApplicationId { get; set; }
[Required]
public string AppName { get; set; }
[Required]
public string PublisherEmail { get; set; }
public string Genre { get; set; }
public string Price { get; set; }
public string Description { get; set; }
public string Version { get; set; }
public string IconUrl { get; set; }
public string PublisherName { get; set; }
public string AllRatingCount { get; set; }
public string AllRating { get; set; }
//One(UserProfile) To Many(AppInfo)
public int UserProfileId { get; set; }
public UserProfile UserProfile { get; set; }
public IEnumerable<Review> Reviews { get; set; }
}
OnModelCreating
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().
HasOne<UserProfile>(s=>s.UserProfile).
WithOne(s=>s.User).
HasForeignKey<UserProfile>(s=>s.UserId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<ApplicationInfo>()
.HasOne<UserProfile>(s => s.UserProfile)
.WithMany(s => s.ApplicationInfos)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Review>()
.HasOne<UserProfile>(s => s.UserProfile)
.WithMany(s => s.Reviews)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Review>()
.HasOne<ApplicationInfo>(s => s.ApplicationInfo)
.WithMany(s => s.Reviews)
.OnDelete(DeleteBehavior.Cascade);
}
Just Change OnModelCreating and change OnDelete for Review and AppInfo to Restrict(No Action)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOne<UserProfile>(s => s.Profile)
.WithOne(s => s.User)
.HasForeignKey<UserProfile>(s=>s.UserId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<ApplicationInfo>()
.HasOne<UserProfile>(s => s.UserProfile)
.WithMany(s => s.ApplicationInfos)
.HasForeignKey(s => s.UserProfileId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Review>()
.HasOne<UserProfile>(s => s.UserProfile)
.WithMany(s => s.Reviews)
.HasForeignKey(s => s.UserProfileId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Review>()
.HasOne<ApplicationInfo>(s => s.ApplicationInfo)
.WithMany(s => s.Reviews)
.HasForeignKey(s => s.ApplicationInfoId)
.OnDelete(DeleteBehavior.Restrict);
base.OnModelCreating(modelBuilder);
}

ArgumentNullException: Value cannot be null. Parameter name: key on Include Statement

Worked a lot with EF 6.x (via designer) and now started on a new project using EF Core.
I'm getting an error that says value cannot be null, not sure exactly what I'm doing wrong. I've got rid of a lot of fields for brevity as there are hundreds.
All these tables are views via synonyms that connect to a different database. I can get it to work fine, if I do each individual call to a database, but as soon as I do include. I get an error on that line. The error I'm getting is
ArgumentNullException: Value cannot be null.
Parameter name: key
System.Collections.Generic.Dictionary.FindEntry(TKey key)
OnGetAsync
var equipment = _context.EMEMs.Include(x => x.EMEDs).Where(x => x.KeyID.ToString() == key);
EMEM = await equipment.Include(x => x.EMCM).ThenInclude(x=>x.EMCDs).FirstOrDefaultAsync();
EMEM
public class EMEM
{
public byte? EMCo { get; set; }
[Display(Name = "Equipment Code")]
public string Equipment { get; set; }
public string Type { get; set; }
public string Category { get; set; }
public Guid? UniqueAttchID { get; set; }
[Key]
public long KeyID { get; set; }
[NotMapped] public string EquipmentDetails => $"{Equipment.Trim()} - {Description} - {VINNumber}";
public virtual IEnumerable<EMWH> EMWHs { get; set; }
public virtual EMCM EMCM { get; set; }
public virtual IEnumerable<udEMED> EMEDs { get; set; }
}
EMCM
public class EMCM
{
[Key]
public long KeyID { get; set; }
public byte? EMCo { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public string Notes { get; set; }
public virtual IEnumerable<EMEM> EMEMs { get; set; }
public virtual IEnumerable<udEMCD> EMCDs { get; set; }
}
udEMCD
public class udEMCD
{
[Key]
public long KeyID { get; set; }
public byte? Co { get; set; }
public string Category { get; set; }
public string DocumentCategory { get; set; }
public int Seq { get; set; }
public Guid? UniqueAttchID { get; set; }
public virtual udEMDC EMDC { get; set; }
public virtual EMCM EMCM { get; set; }
public virtual IEnumerable<HQAT> HQATs { get; set; }
}
Context
modelBuilder.Entity<EMEM>().ToTable("EMEM").HasOne(x => x.EMCM).WithMany(x => x.EMEMs).HasForeignKey(x => new { x.EMCo, x.Category }).HasPrincipalKey(x => new { x.EMCo, x.Category });
modelBuilder.Entity<EMEM>().ToTable("EMEM").HasMany(x => x.EMEDs).WithOne(x => x.EMEM).HasForeignKey(x => new { x.Co, x.Equipment }).HasPrincipalKey(x => new { x.EMCo, x.Equipment });
modelBuilder.Entity<EMCM>().ToTable("EMCM").HasMany(x => x.EMCDs).WithOne(x => x.EMCM)
.HasForeignKey(x => new { x.Co, x.Category }).HasPrincipalKey(x => new { x.EMCo, x.Category });
modelBuilder.Entity<udEMCD>().ToTable("udEMCD").HasOne(x => x.EMDC).WithMany(x => x.EMCDs)
.HasForeignKey(x => x.DocumentCategory).HasPrincipalKey(x => x.Category);
modelBuilder.Entity<udEMDC>().ToTable("udEMDC").HasMany(x => x.EMEDs).WithOne(x => x.EMDC).HasForeignKey(x => new{ x.DocumentCategory}).HasPrincipalKey(x => new{ x.Category});
modelBuilder.Entity<udEMED>().ToTable("udEMED");
modelBuilder.Entity<EMWH>().ToTable("EMWH");
modelBuilder.Entity<EMWI>().ToTable("EMWI");
modelBuilder.Entity<HQAT>().HasOne(x => x.EMWH).WithMany(x => x.HQATs).HasForeignKey(x => x.UniqueAttchID)
.HasPrincipalKey(x => x.UniqueAttchID);
modelBuilder.Entity<EMWH>().HasOne(x => x.EMEM).WithMany(x => x.EMWHs)
.HasForeignKey(x => new {x.EMCo, x.Equipment}).HasPrincipalKey(x => new {x.EMCo, x.Equipment});
EDIT: I added nullable KeyID's just to test prior to uploading and still didn't work.
I think the error is that you're declaring the Key as nullable, which it should never happen.
[Key]
public long? KeyID { get; set; }
change your code to this...
[Key]
public long KeyID { get; set; }

Categories

Resources