I am quite new to this code-first pattern.
I have created a class and now I want to create a table in my database.
in the PM console i wrote 'add migration addSummaries' and hit enter.
and i have the following error:
PM> add-migration addsummaries
System.ArgumentNullException: Value cannot be null.
Parameter name: key
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at System.Data.Entity.ModelConfiguration.Configuration.Mapping.SortedEntityTypeIndex.Add(EdmEn titySet entitySet, EdmEntityType entityType)
at System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Analyze()
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes (DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabase Mapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.get_CodeFirstModel()
at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
at System.Data.Entity.Migrations.Extensions.DbContextExtensions.<>c__DisplayClass1. <GetModel>b__0(XmlWriter w)
at System.Data.Entity.Migrations.Extensions.DbContextExtensions.GetModel(Action`1 writeXml)
at System.Data.Entity.Migrations.Extensions.DbContextExtensions.GetModel(DbContext context)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.GetPendingMigrationsRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
Value cannot be null.
Parameter name: key
PM>
i have no clue what does it mean..can anybody help me to find the actual error??
EDIT:
public class Summary
{
[Key]
public int Id { get; set; }
public Guid SummaryId { get; set; }
[Required]
[Display(Name="Title")]
[MaxLength(500)]
public string SummaryTitle { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
public DateTime PublishDate { get; set; }
public virtual UserProfile Writer { get; set; }
public bool PublishStatus { get; set; }
[Required]
public DateTime LastActionDate { get; set; }
public HttpPostedFileBase DocumentFile { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
[Required]
public string Tag { get; set; }
public virtual ICollection<Course> Category { get; set; }
}
If you have a class inherited from the "Summary" class, and it references anthor custom class that is not contained in your DbContext, you will encounter this issue.
Related
Source code for this problem is on GitHub
I have the following dbContext for a legacy data structure.
[TypesInfoInitializer(typeof(OrgsContextInitializer))]
public class OrgsEFCoreDbContext : DbContext
{
public OrgsEFCoreDbContext(DbContextOptions<OrgsEFCoreDbContext> options) : base(options)
{
}
public DbSet<ModuleInfo> ModulesInfo { get; set; }
public DbSet<ModelDifference> ModelDifferences { get; set; }
public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
public DbSet<PermissionPolicyRole> Roles { get; set; }
public DbSet<ApplicationUser> Users { get; set; }
public DbSet<ApplicationUserLoginInfo> UserLoginInfos { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<CustomerContact> CustomerContacts { get; set; }
public DbSet<SupplierContact> SupplierContacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUserLoginInfo>(b =>
{
b.HasIndex(nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.LoginProviderName), nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.ProviderUserKey)).IsUnique();
});
modelBuilder.Entity<Organization>().ToTable("Organizations");
modelBuilder.Entity<Organization>().HasDiscriminator(x => x.OrganizationType)
.HasValue<Customer>(1)
.HasValue<Supplier>(2)
;
modelBuilder.Entity<Contact>().ToTable("Contacts");
modelBuilder.Entity<Contact>().HasDiscriminator(x => x.ContactType)
.HasValue<CustomerContact>(1)
.HasValue<SupplierContact>(2)
;
}
}
When I add a CustomerContact to a Customer I get an error
Unable to cast object of type 'Orgs.Module.BusinessObjects.CustomerContact' to type 'Orgs.Module.BusinessObjects.SupplierContact'.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.get_Item(IPropertyBase propertyBase)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.GetCurrentValue(IPropertyBase propertyBase)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.TryAddPropertyNameToCollection(InternalEntityEntry entity, ICollection`1 propertiesToCheck, IPropertyBase property)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.TryAddPropertyNameToCollection(InternalEntityEntry entity, IProperty property, ICollection`1 propertiesToCheck)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.GetPropertiesToCheck(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckReadWritePermissionsForNonIntermediateObject(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckReadWritePermissions(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckIsGrantedToSave(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.GetEntriesToSave(Boolean cascadeChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at DevExpress.ExpressApp.EFCore.EFCoreObjectSpace.DoCommit()
at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpace.DoCommit()
at DevExpress.ExpressApp.BaseObjectSpace.CommitChanges()
at DevExpress.ExpressApp.Win.SystemModule.WinModificationsController.Save(SimpleActionExecuteEventArgs args)
at DevExpress.ExpressApp.SystemModule.ModificationsController.saveAction_OnExecute(Object sender, SimpleActionExecuteEventArgs e)
at DevExpress.ExpressApp.Actions.SimpleAction.RaiseExecute(ActionBaseEventArgs eventArgs)
at DevExpress.ExpressApp.Actions.ActionBase.ExecuteCore(Delegate handler, ActionBaseEventArgs eventArgs)
The error is the other way around if I try to add a supplier contact to a supplier.
The business classes are as follows;
[NavigationItem("Data")]
public class Customer : Organization
{
public Customer()
{
Contacts = new List<CustomerContact>();
}
public virtual List<CustomerContact> Contacts { get; set; }
}
public class CustomerContact : Contact
{
public CustomerContact() {}
[ForeignKey("OrganizationId")]
public virtual Customer Customer { get; set; }
}
public abstract class Organization
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Comments { get; set; }
public int OrganizationType { get; set; }
}
public abstract class Contact
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int ContactType { get; set; }
public int OrganizationId { get; set; }
}
At run time the user experience is
Looking at the instructions here I am unsure if this is a Dev Express issue or an Entity Framework issue.
While I am going to add-migration it's ok but while I am going to run update-database I am getting this type of error in package manager console
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.ServiceTypes_dbo.Services_ServiceTypeID". The conflict occurred in database "Otaidea", table "dbo.Services", column 'ServicesID'.
My two model:
public class Services
{
[Key]
public int ServicesID { get; set; }
[DisplayName("Register Date")]
public DateTime RegisterDate { get; set; }
public int ServiceTypeID { get; set; }
public string ApplicationUserID { get; set; }
public virtual ServiceType ServiceType { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
my another Table:
public class ServiceType
{
[ForeignKey("Services")]
public int ServiceTypeID { get; set; }
public string NAME { get; set; }
public virtual Services Services { get; set; }
}
Your relationship in your models are wrong. Services has a "Type", so the Foreign Key goes from ServiceType to Service. You don't need to reference Services inside ServiceType
You should create your model like this:
Services
public class Services
{
[Key]
public int ServicesID { get; set; }
[DisplayName("Register Date")]
public DateTime RegisterDate { get; set; }
public string ApplicationUserID { get; set; }
[ForeignKey("ServiceType")]
public int ServiceTypeID { get; set; }
public virtual ServiceType ServiceType { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
ServiceType
public class ServiceType
{
[Key]
public int ServiceTypeID { get; set; }
public string NAME { get; set; }
}
I would also do the same with the ApplicationUserID property, but since you didn't post about it I let it as is.
Also, it would be better if you drop your database and let Entity Framework create it again for you. Because you had a wrong model relationship things got "messy".
I am new to entity framework. I have following models.
public partial class PropertyDetail
{
public int PropertyID { get; set; }
public string PropertyName { get; set; }
public virtual PropertyAddress PropertyAddress { get; set; }
public string AnalyticsView { get; set; }
public string MoreInformationLink { get; set; }
}
public class PropertyAddress
{
public string PropertyName { get; set; }
public string StreetAddress { get; set; }
public string PostalCode { get; set; }
public virtual PropertyDetail PropertyDetail { get; set; }
}
I want PropertyID from PropertyDetail to be primary key and PropertyName to be Foreign key in PropertyAddress table.
Thank for help.
with EF6 you can't: the FK must be of the same type as the PK. I heard about that in EF7 but not for sure.
I am new to EF and am having trouble figuring how to set up relationship between my main table Investors, with contact information, and a table Notes which can have many notes per investor. Here are the models:
public class Investor
{
public int Id { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Cell { get; set; }
public string Fax { get; set; }
[Display(Name="Address 1")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
[StringLength(2, ErrorMessage = "State must be 2 characters")]
public string State { get; set; }
public string Zip { get; set; }
public string ContactTableId { get; set; }
[ForeignKey("ContactTableId, ContactId")]
public virtual List<Note> Notes { get; set; }
}
public class Note
{
[Key]
[Column(Order = 0)]
public string ContactTableId { get; set; }
[Key]
[Column(Order = 1)]
public int? ContactId { get; set; }
public string note { get; set; }
public DateTime? DateCreated { get; set; }
}
My attempt as setting this up, as above, generated the error 'The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.' on the statement:
public ActionResult Index()
{
return View(db.Investors.ToList());
}
in the controller. How do I set this up to make it pull the Notes automagically.
The foreign key is not "ContactTableId, ContactId", it is the single field Investor_Id in table Note (or Notes). EF thinks you try to map the single key to two field and coins this somewhat elusive exception message. But just remove the ForeignKey attribute and EF will use the foreign key field in Note.
I have nested object in EF Code First using Silverlight RIA service, I am able to get the data at service side but when I see it on client side child objects are null. Could you please guide me what's wrong.
[HasSelfValidation]
public class Batch
{
public int BatchId { get; set; }
public string BatchName { get; set; }
[Include]
[Composition]
[Association("FK_Batch_BathSetItemSet", "BatchId", "BatchSetIdItemSetId")]
public virtual ICollection<BatchSetItemSet> BatchSetItemSets { get; set; }
}
public class BatchSetItemSet
{
public int BatchSetIdItemSetId { get; set; }
public int BatchId { get; set; }
public Nullable<int> ItemSetId { get; set; }
public string CreatedBy { get; set; }
public Batch Batch { get; set; }
[Include]
[Composition]
[Association("FK_BathSetItemSet_ItemSet", "BatchSetIdItemSetId", "ItemSetId")]
public ItemSet ItemSet { get; set; }
}
public class ItemSet
{
public int ItemSetId { get; set; }
public int CustodianId { get; set; }
public string ItemSetName { get; set; }
public virtual ICollection<BatchSetItemSet> BatchSetItemSets { get; set; }
[Include]
[Composition]
[Association("FK_ItemSet_Custodian", "ItemSetId", "CustodianId")]
public virtual Custodian Custodian { get; set; }
}
and service call is : this.DbContext.Batches.Include("BatchSetItemSets.ItemSet.Custodian").Where(x => x.BatchId == batchId).SingleOrDefault();
You are close with the attributes, but they need to be changed:
[HasSelfValidation]
public class Batch
{
public int BatchId { get; set; }
public string BatchName { get; set; }
[Include]
[Composition]
[Association("FK_Batch_BathSetItemSet", "BatchId", "BatchId", IsForeignKey = false)]
public virtual ICollection<BatchSetItemSet> BatchSetItemSets { get; set; }
}
public class BatchSetItemSet
{
public int BatchSetIdItemSetId { get; set; }
public int BatchId { get; set; }
public Nullable<int> ItemSetId { get; set; }
public string CreatedBy { get; set; }
[Include]
[Association("FK_Batch_BathSetItemSet", "BatchId", "BatchId")]
public Batch Batch { get; set; }
[Include]
[Association("FK_BathSetItemSet_ItemSet", "ItemSetId", "ItemSetId")]
public ItemSet ItemSet { get; set; }
}
public class ItemSet
{
public int ItemSetId { get; set; }
public int CustodianId { get; set; }
public string ItemSetName { get; set; }
[Include]
[Composition]
[Association("FK_BathSetItemSet_ItemSet", "ItemSetId", "ItemSetId", IsForeignKey = false)]
public virtual ICollection<BatchSetItemSet> BatchSetItemSets { get; set; }
[Include]
[Association("FK_ItemSet_Custodian", "CustodianId", "CustodianId")]
public virtual Custodian Custodian { get; set; }
}
The AssociationAttribute .ctor is defined as:
AssociationAttribute(string name, string thisKey, string otherKey)
It should be configured as:
name: A unique name shared by each end of the relationship
thisKey: The name of the Property on this object that represents the key or foreign key
otherKey: The name of the Property on the other object that represents the key or foreign key
IsForeignKey: A property on AssociationAttribute to indicate if this end of the relationship is the primary key or the foreign key. It defaults to true (meaning this navigation property is a Foreign Key). By setting it to false, you indicate to WCF RIA that this object contains the Primary Key. For all AssociationAttribute usages with a given name, only one is allowed to have IsForeignKey = false. Otherwise, you will get a build error.