I am using Entity Framwork DbContexts with a legacy database. I have 2 different properties of an entity that both need to reference the same lookup table, like so:
public class Address
{
public virtual AddressType AnAddressType {get; set;}
public virtual AddressType AnotherAddressType {get; set;}
}
// now here's a LINQ query that just flat won't work:
from a in Addresses select a;
The exception indicates that we tried to include a completely fictional field in the select list -- the field doesn't appear in my POCO or the table -- it looks like it was expected by convention, it's named AnAddressType_AddressType or something close to that
The AddressType entity does not have a corresponding navigation property on it. I cannot seem to get this to work. When I attempt to select data with my LINQ query, I get runtime errors.
Edit
I have other relations that are working (this code is generated from the "stock" DbContext generator). The thing about this one relation that is different is that the lookup table does not have a navigation property back to the main table (the lookup table is used all over the place, so I don't really want to add nav properties from it to everything that uses it). EF seems to be having a problem with that. It's probably a configuration vs. convention thing, and I have inadvertently tripped on some kind of convention problem.
You have a foreign key column name in your legacy database which doesn't follow the EF conventions, for example: The foreign key column in your Addresses table to the AddressTypes table for the AnAddressType relationship has the name MyCrazyAnAddressTypeNumberCodeKeyId.
But EF will assume by convention that the FK column name is: [Nav.property]_[KeyColumn]. For example: If AddressType has a PK with name AddressTypeId EF will assume the FK column has the name AnAddressType_AddressTypeId. Because this doesn't match you get the exception you describe. You must specify the FK column name explicitely to fix this problem:
modelBuilder.Entity<Address>()
.HasRequired(a => a.AnAddressType)
.WithMany()
.Map(c => c.MapKey("MyCrazyAnAddressTypeNumberCodeKeyId"))
.WillCascadeOnDelete(false);
(code snippet partially stolen from Ladislav's answer for convenience)
That's my hypothesis.
Edit
Alternatively you can introduce a foreign key property into your model and tell EF by data annotations that this property is a FK to the corresponding navigation property:
public class Address
{
[ForeignKey("AnAddressType")]
public int MyCrazyAnAddressTypeNumberCodeKeyId {get; set;}
public virtual AddressType AnAddressType {get; set;}
}
If you don't want navigation properties on both sides of the relation you should help EF with fluent mapping so that model is represented correctly:
public class YourContext : DbContext
{
public DbSet<Address> Addresses { get; set; }
public DbSet<AddressType> AddresTypes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Address>()
.HasRequired(a => a.AnAddressType)
.WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Address>()
.HasRequired(a => a.AnotherAddressType)
.WithMany()
.WillCascadeOnDelete(false);
}
}
Related
I have the following entity declared
public class TransactionEvent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public virtual List<TransactionSignInError> SignInErrors { get; set; }
}
And the context
public class TransactionAuditsDbContext : DbContext
{
public virtual DbSet<TransactionEvent> TransactionEvents { get; set; }
}
Now when I try to delete a transaction event, I want the relevant SignInError rows to be deleted as well. I realize I can do this by using cascade on delete if I had set that up in the context, too late for that now.
How can I delete successfully a transaction? I'm getting this error.
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.TransactionSignInErrors_dbo.TransactionEvents_TransactionEvent_Id". The conflict occurred in database "db", table "dbo.TransactionSignInErrors", column 'TransactionEvent_Id'
I have tried clearing the SignInErrors list before deleting, that did get rid of the above error but left NULLs in the TransactionSignInErrors table.
What you want, is "Cascade on Delete": if a TransactionEvent is deleted, then you also want that all its TransactionSignInErrors are deleted.
This works on a one-to-many relation, this does not work on a many-to-many-relation.
If you have a one-to-many relation between TransactionEvents and TransactionSignInErrors, and you followed the entity framework conventions, you will have classes like
public class TransactionEvent
{
public Guid Id { get; set; }
...
// Every TransactionEvent has zero or more TransactionSignInErrors (one-to-many)
public virtual ICollection<TransactionSignInError> SignInErrors { get; set; }
}
public class TransactionSignInError
{
public Guid Id { get; set; }
...
// Every TransactionSignInError belongs to exactly oneTransactionEvent, using foreign key
public Guid TransactionEventId {get; set;}
public virtual TransactionEvent TransactionEvent { get; set; }
}
public class TransactionAuditsDbContext : DbContext
{
public DbSet<TransactionEvent> TransactionEvents { get; set; }
public DbSet<TransactionSignInError> TransactionSignInErrors {get; set;}
}
This is all that entity framework needs to know to detect the tables, the columns in the tables and the one-to-many relation between these two tables.
In entity framework the non virtual properties represent the columns in the table, the virtual properties represent the relations between the tables (one-to-many, many-to-many, ...)
The foreign key TransactionEventId is a real column, hence it is non-virtual. TransactionEvent is not a real column, it only refers to the relation, hence it is declared virtual.
If you stick to the conventions, there is no need for attributes, nor fluent API. Only if you want non-default identifiers for tables, columns, column types or non-default behaviour for table relations, you might need attributes or fluent API.
Default behaviour is cascade on delete: if you delete a TransactionEvent, all its TransactioinSigninErrors are also deleted.
I'm not sure whether your problems arise because you have a GUID as primary key, instead of an int. If you want, you can inform entity framework about your one-to-many relation and cascade on delete in OnModelCreating:
protected override void OnModelCreating (DbModelBuilder modelBuilder)
{
// Every TransactionEvent has zero or more TransactionSignInErrors
// Every TransactionSignInError belongs to exactly one TransactionEvent
// using foreign key TransactionEventId.
// Also: cascade on delete:
modelBuilder.Entity<TransactionEvent>()
.HasMany(transactionEvent => transactionEvent.TransactionSignInErrors)
.WithRequired(transactionSignInError => transactionSignInError.TransactionEvent)
.HasForeignKey(transactionSignInError => transactionSignInError.TransactionEventId)
.WillCascadeOnDelete();
So three major changes to your code:
The DbSets in the DbContext are non-virtual
Added the table TransactionSignInErrors to your DbContext
If that is not enough for CascadeOnDelete (check this first!) add fluent API.
Small change: Use ICollection instead of IList.
Rationale: if you fetch a TransactionEvent with its TransactionSignInErrors, does TransactionEvent.SignInErrors[4] have a defined meaning? Wouldn't it be better if people have no access to methods that they don't know what they really mean?
If you want to use a cascade delete you have to include the children:
var removingRow=_context.Set<TransactionEvent>()
.Include(x=> x.SignInErrors )
.Where(x => x.Id ==id)
.FirstOrDefault();
if(removingRow != null)
{
_context.Remove(removingRow);
_context.SaveChanges();
}
Your post has the tag of entity-framework. I'm not sure how things work with Entity Framework 6 or previous versions, but with Entity Framework Core you can solve your issue like -
var tEvent = dbCtx.TransactionEvents
.Include(p=> p.SignInErrors)
.FirstOrDefault(p => p.Id == id);
foreach (var error in eventx.SignInErrors)
{
dbCtx.SignInErrors.Remove(error);
}
dbCtx.TransactionEvents.Remove(tEvent);
dbCtx.SaveChanges();
In database, I have two tables - Show and Language. Table Show besides other things has Foreign Key to Language. Its one-to-many relationship (Show has one language).
When I run Code First from ADO.NET Entity Data Model creates two properties for language field:
public class ShowModel
{
...
public LanguageModel Language1 {get; set;}
public string Language {get; set;}
...
}
public class LanguageModel
{
...
public string Language {get; set;}
...
}
When I debug on sample data, value of Language field from DB is inserted into string property.
Question is - Why it generates those properties? Is it because I can add Language object into the LanguageModel one, but from DB, it always write to string one?
EDIT
modelBuilder.Entity<LanguageModel>()
.HasMany(e => e.Shows)
.WithOptional(e => e.Language1)
.HasForeignKey(e => e.Language);
modelBuilder.Entity<ShowModel>()
.Property(e => e.Language)
.IsUnicode(false);
If you are hinting at the fact that the field 'Language' is the foreign key to the Language table for the 'Laguage1' navigation property, then I can give you a couple of pointers:
The key in the Language table is your Language property, but might not be marked as the key. EF doesn't figure this out by itself unless you name the field Id or something, or mark it with a [Key] attribute.
EF doesn't see the 'Language' field as the Foreign key, but as another scalar property, this will result in having 2 Language fields on the Show property. This can be solved by telling the ModelBuilder to use the proper navigation property.
The syntax to solve no. 2 is similar to this:
modelBuilder.Entity<ShowModel>()
.HasRequired(t => t.Language1)
.WithMany(t => t.Shows)
.HasForeignKey(d => d.Language);
pulling my hair out on this...I have a code-first entity model for oracle, and I am having problems getting around this foreign key issue:
"The property 'aidYearCode' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type."
Here are the relevant code snippets:
1) in "OnModelCreating(DbModelBuilder modelBuilder)":
modelBuilder.Entity<INSTITUTIONAL>()
.HasMany(e => e.applicantBudgetComponents)
.WithRequired(e => e.institutional) // so this exists in APPLICANT_BUDGET_COMPONENTS: public virtual INSTITUTIONAL institutional { get; set; }
.HasForeignKey(e => e.aidYrCode)
.WillCascadeOnDelete(false);
2) the table APPLICANT_BUDGET_COMPONENTS with the foreign key has:
[Key]
[Column(Order = 0)]
[StringLength(4)]
public string aidYrCode { get; set; }
3) lastly the INSTITUTIONAL table has the primary key:
[Key]
[StringLength(4)]
public string aidYearCode { get; set; }
This was all generated by the Code-First wizard in VS2015, here is what I have tried:
putting the annotation
[ForeignKey("aidYrCode")] in 2)
putting the annotation from oracle's schema in 2)
[ForeignKey("FK1_RBRACMP_INV_ROBINST_CODE")]
adding "Id" to Foreign Key Names so as to follow EF6 conventions.
it should be noted that APPLICANT_BUDGET_COMPONENTS has a composite primary key.
It turns out that the error message was spurious; the configuration of "aidYearcode" was correct, however, after digging deeper I found some missing model configurations in other tables (indirectly related to the ones mentioned here) and after inserting the proper fluent commands and attributes for those properties the "error" was resolved.
I am using entity framework 4, mvc4 and code first.
I'm struggling with creating an option 1:1 mapping, where the main entity that has the optional 1:1 mapping doesn't have the FK in it:
public class User
{
[Column("user_id")]
public int Id {get;set;}
public virtual House House {get;set;} // optional mapping
}
public class House
{
[Column("house_id")]
public int Id {get;set;}
[Column("user_id")]
public int UserId {get;set;}
}
Notice how the user table doesn't have teh houseId column.
How can I map this correctly?
Note: the below method isn't what i really want to do since it forces me to add a navigational property on the House model also back to User.
I tried this method, although I had to add a virtual property to the House model which I didn't want to do: How do I code an optional one-to-one relationship in EF 4.1 code first with lazy loading and the same primary key on both tables?
So my configuration looks like with the above attempt:
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
this.ToTable("User", SchemaName);
this.HasKey(x => x.Id);
this.HasOptional(x => x.House);
}
}
public class HouseConfiguration : EntityTypeConfiguration<House>
{
public HouseConfiguration()
{
this.ToTable("House", SchemaName);
this.HasKey(x => x.Id);
this.HasRequired(vc => vc.User).WithRequiredDependent(v => v.House);
}
}
But when I do this, saving the model I get this error:
Cannot insert explicit value for identity column in table 'House' when IDENTITY_INSERT is set to OFF
Note: without the above setup (mapping and configuration), the House entity saves just fine to the database and the identity is setup correctly.
Remove the UserId property from House, remove the this.HasRequired... mapping from the HouseConfiguration constructor and use in UserConfiguration:
this.HasOptional(x => x.House).WithRequired();
This will define a shared primary key association (i.e. House.Id is primary key of House and the foreign key to User at the same time).
If you have an existing database with a separate foreign key column user_id in the House table and this column has a unique key constraint to enforce a one-to-one relation in the database you cannot map this as one-to-one relationship with Entity Framework because EF doesn't support foreign key one-to-one associations.
You would have to map this as one-to-many relationship in this case and unfortunately you can't have a single reference House on the principal User. You would have to use a collection of Housees instead (and ensure in business logic that you never add more than one element to this collection, otherwise upon saving you would get an exception due to a violation of the unique FK constraint in the House table) or no navigation property at all in User. But then you need a navigation reference User in entity House so that EF would be able to map a relationship at all (at least a navigation property on one side of a relationship is always needed).
Can't rollback to EF4, but was only using it in a similar way a while ago, so don't believe this has changed.
You need to set a Key on the House object and set it to DB generated:
using System.ComponentModel.DataAnnotations.Schema
using System.ComponentModel.DataAnnotations
...
public class House
{
[Column("house_id")]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("user_id")]
public int UserId { get; set; }
}
I'm using entity framework code-first to create my database schema automatically, and one of my entities looks like this:
public class AssessmentsCaseStudies {
#region Persisted fields
[Required]
[Key, Column(Order=0)]
[ForeignKey("Assessment")]
public int AssessmentId { get; set; }
[Required]
[Key, Column(Order=1)]
[ForeignKey("CaseStudy")]
public int CaseStudyId { get; set; }
[Required]
public int Score { get; set; }
[ForeignKey("Follows")]
public int? FollowsCaseStudyId { get; set; }
#endregion
#region Navigation properties
public virtual Assessment Assessment { get; set; }
public virtual CaseStudy CaseStudy { get; set; }
public virtual CaseStudy Follows { get; set; }
#endregion
}
When EF auto-generates my database, it generates a table with the following columns:
AssessmentId (PK, FK, int, not null)
CaseStudyId (PK, FK, int, not null)
Score (int, not null)
FollowsCaseStudyId (FK, int, null)
CaseStudy_CaseStudyId (FK, int, null)
This is all fine apart from the CaseStudy_CaseStudyId column. Why has that been generated? What is it for? How can I stop it being generated? My suspicion is that EF can no longer automatically match up CaseStudy's ICollection<AssessmentsCaseStudies> with the CaseStudyId column, so it creates its own column to link the two together for that navigation property.
Because you have two navigation properties of type CaseStudy in your AssessmentsCaseStudies entity and an AssessmentsCaseStudies collection in your CaseStudy entity EF cannot decide which of the two CaseStudy navigation properties this collection refers to. Both could be possible and both options would result in a valid but different entity model and database schema.
In such an ambiguous situation the EF convention is to create actually three relationships, i.e. your collection in CaseStudy does not refer to any of the two CaseStudy navigation properties but has a third (but not exposed and "invisible") endpoint in AssessmentsCaseStudies. This third relationship is the reason for the third foreign key your are seeing in the database - the one with the underscore. (The underscore is always a strong indication that something happend by mapping convention and not by your explicit configuration or data annotations.)
To fix the problem and to override the convention you can apply the [InverseProperty] attribute, thereby specifying the CaseStudy navigation property the AssessmentsCaseStudies collection belongs to:
[InverseProperty("AssessmentsCaseStudies")] // the collection in CaseStudy entity
public virtual CaseStudy CaseStudy { get; set; }
You can also (alternatively, you don't need both) put the attribute on the collection side:
[InverseProperty("CaseStudy")] // the CaseStudy property in AssessmentsCaseStudies entity
public virtual ICollection<AssessmentsCaseStudies> AssessmentsCaseStudies { get; set; }
For some reason, Slauma's InverseProperty attribute suggestion didn't work. What did work was me specifying the relationship between the two CaseStudy navigation properties in AssessmentsCaseStudies, and the CaseStudy entity, via the Fluent API in my database context's OnModelCreating method:
modelBuilder.Entity<AssessmentsCaseStudies>()
.HasRequired(acs => acs.CaseStudy)
.WithMany(cs => cs.AssessmentsCaseStudies)
.HasForeignKey(acs => acs.CaseStudyId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<AssessmentsCaseStudies>()
.HasOptional(acs => acs.Follows)
.WithMany() // No reverse navigation property
.HasForeignKey(acs => acs.FollowsCaseStudy)
.WillCascadeOnDelete(false);
Once that's added, the migration code that's generated when I Add-Migration no longer tries to add the CaseStudy_CaseStudyId column and I just get the FollowsCaseStudyId column added, with the appropriate foreign key relationship.
For anyone else landing here looking for a solution, if you've tried the previous answers and are still getting an extra foreign key column, look for any properties you may have defined further down your POCO class that you did not intend to map to DB fields. Even if they contain code blocks, as with complex get accessors, Entity Framework will try to map them to the database somehow. This may result in extra foreign key columns if your properties return entities. To be safe, either decorate such properties with the [NotMapped] attribute or convert them to methods.