Entity Framework: Two foreign keys connected by one collection - c#

I know that there is related topic: two Foreign Keys from same table, but I can't find there fix to my problem. I am pretty new to EF.
I have the following model classes (Code-First):
public class Member
{
[Key]
public int MemberID { get; set; }
public string Name {get; set;}
public string Surname { get; set; }
public virtual ICollection<Marriage> Marriages { get; set; }
}
public class Marriage
{
[Key]
public int MarriageID { get; set; }
public string MarriagePlace { get; set; }
public DateTime MarriageDate { get; set; }
[ForeignKey("Husband")]
public int HusbandID { get; set; }
[ForeignKey("Wife")]
public int WifeID { get; set; }
public virtual Member Husband { get; set; }
public virtual Member Wife { get; set; }
}
My problem is that both Husband and Wife should be connected to the same Marriage collection in Member class. I did that:
modelBuilder.Entity<Marriage>()
.HasRequired<Member>(m => m.Husband)
.WithMany(m => m.Marriages)
.HasForeignKey(m => m.HusbandID)
.WillCascadeOnDelete(false);
And husband is now connected to Merriages collection. But everything breaks when I'm trying to add the same thing for Wife property:
modelBuilder.Entity<Marriage>()
.HasRequired<Member>(m => m.Wife)
.WithMany(m => m.Marriages)
.HasForeignKey(m => m.WifeID)
.WillCascadeOnDelete(false);
and I am getting an error:
Error 1 Schema specified is not valid. Errors: The relationship 'FamilyTree.Models.Marriage_Husband' was not loaded because the type 'FamilyTree.Models.Member' is not available. C:\Users\Sumiteru\Documents\Visual Studio 2013\Projects\FamilyTree\FamilyTree\App.xaml 9 21 FamilyTree

That error occurs becouse EF didn't know what navigation property he must use. In OnModelBuliding method you are setting a Member's foreign key to Marriages twice, so EF is confused about what navigation property should use when it will populating Marriages and throws an exception.
There's a topic on EF codeplex forum, where user named 'moozzyk' explains that EF behavior more clearly (in comment): Link.
As a solution, You should do another collection navigation property in Member class and map Wife's or Husbend's foreign key to it. You can find the same solution on that SO anwser: Link.

Related

entities that do not expose foreign key properties for their relationships (EF) [duplicate]

This question already has answers here:
An error occurred while saving entities that do not expose foreign key properties for their relationships
(16 answers)
Closed 2 months ago.
When trying to call SaveChanges(), I get the following error:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.'
SqlException: Invalid column name 'Artwork_Id'
I am using Entity Framework.
I'm trying to add an artworkImage that has the Id of an artwork as a reference. All information is being passed correctly but it's not saving.
I've tried adding foreign keys to my models and dbcontext but I've not gotten further than the code below.
public partial class ArtworkImage
{
[Key]
public int Id { get; set; }
public string ImageURL { get; set; }
public Artwork Artwork { get; set; }
}
public partial class Artwork
{
[Key]
public int Id { get; set; }
public string Category { get; set; }
public ICollection<ArtworkImage> ArtworkImage { get; set; }
}
My DbContext:
public DbContext()
: base("name=DbConnection")
{
this.Configuration.AutoDetectChangesEnabled = false;
}
public virtual DbSet<Artwork> Artworks { get; set; }
public virtual DbSet<ArtworkImage> ArtworkImages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Artwork>()
.Property(e => e.Category)
.IsFixedLength();
modelBuilder.Entity<Artwork>()
.HasKey(b => b.Id);
modelBuilder.Entity<ArtworkImage>()
.HasKey(b => b.Id);
Database.SetInitializer<DbContext>(null);
base.OnModelCreating(modelBuilder);
}
I believe I should be adding something like this to my dbcontext but I haven't quite figured it out yet.
modelBuilder.Entity<ArtworkImage>()
.HasRequired(p => p.Artwork)
.WithMany(d => d.ArtworkImage)
.HasForeignKey(p => p.Artwork);
If any information is missing please point it out and I'll add it.
You have to declare primary key on each table. it is a rare occasion when a table has no PK. almost never.
[Key]
public int Id { get; set; }
So part of your problem might be that you don't define the relationship in reverse which I believe is important in how it establishes if the relationship is one-to-one or one-to-many. So you will likely need to add a property on the Artwork class that is of type ArtworkImage (if it is one-to-one). if it is one-to-many you will need to make the property some generic collection with the generic of type ArtworkImage.
One-to-one
public partial class Artwork
{
[Key]
public int Id { get; set; }
public string Category { get; set; }
public ArtworkImage ArtworkImage { get; set; }
}
One-to-many
public partial class Artwork
{
[Key]
public int Id { get; set; }
public string Category { get; set; }
public IEnumerable<ArtworkImage> ArtworkImages { get; set; }
}

One-To-One relationship with FK distinct from PK

I have 2 tables in database: ReceivedGoods and ReceivedGoodsProperties
ReceivedGoods contains ReceivingId as PK and must have its extending data in ReceivedGoodsProperties which contains ReceivingId as FK referencing to the ReceivedGoods's ReceivingId. Current ReceivedGoodsProperties, however, has its own PK Id and is therefore distinct from FK. So I have following:
public class ReceivedGoods
{
...
public int ReceivingId { get; set; }
...
public virtual ReceivedGoodsProperties properties { get; set; }
}
public class ReceivedGoodsProperties
{
...
public int Id { get; set; } // This is PK
public int ReceivingId { get; set; } // This is FK
...
public virtual ReceivedGoods goods { get; set; }
}
I would like to get ReceivedGoods object and have properties automatically loaded as well but I am not able to figure out, how to set up this within EF.
I've tried something like this (from the ReceivedGoodsProperties side mapping):
this.HasRequired(p => p.goods)
.WithRequiredDependent(d => d.properties)
.Map(m => m.MapKey("ReceivingId"));
but I am ending up with following error:
ReceivingId: Name: Each property name in a type must be unique. Property
name 'ReceivingId' is already defined.
When commenting out ReceivingId in ReceivedGoodsProperties, upper exception is not thrown, ReceivedGoods is loaded correctly except the properties property.
Can somebody explain me, how to do one-to-one mapping in situation like this?
Could you try:
public class ReceivedGoods
{
...
public int ReceivingId { get; set; }
...
public virtual ReceivedGoodsProperties properties { get; set; }
}
public class ReceivedGoodsProperties
{
...
public int Id { get; set; } // This is PK
[ForeignKey( "goods " )]
public int ReceivingId { get; set; } // This is FK
...
[Required]
public virtual ReceivedGoods goods { get; set; }
}
BTW, in C# the standard guidelines is to PascalCase members, so Goods and Properties
Try defining the relationship this way:
this.HasRequired(p => p.goods)
.WithRequiredDependent(p => p.properties)
.HasForeignKey(p => p.ReceivingId);
If you follow the standard EF naming conventions, it can usually figure out these relationships on its own. You only really run in to trouble when your navigation property names don't correspond to the class name, or if you have multiple FKs to the same destination in the source table.
If you want the navigation properties to get filled out "automatically", use the Include extension method on the query, as in:context.Goods.Include(g=>g.properties). You don't have to declare them as virtual unless you want to make use of lazy loading.
You may need to come at this from the other entity:
this.HasRequired(p => p.properties)
.WithRequiredPrincipal(p => p.goods)
.HasForeignKey(p => p.ReceivingId);

Entity Framework 1-To-* and 1-to-1

(Entity Framework 6, .NET 4, VS 2010)
I have created a small Blog project to illustrate the problem. This is a Blog that has many posts but only one of the posts act as the main post.
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Post> PostEntities { get; set; }
public int? MainPostId { get; set; }
[ForeignKey("MainPostId")]
public virtual Post MainPostEntity { get; set; } // Problem here
}
public class Post
{
public int Id { get; set; }
public int BlogId { get; set; }
[ForeignKey("BlogId")]
public virtual Blog BlogEntity { get; set; }
public string Title { get; set; }
}
modelBuilder.Entity<Blog>()
.HasOptional(b => b.MainPostEntity)
.WithRequired(p => p.BlogEntity);
static void Main(string[] args)
{
Database.SetInitializer<EFTestContext>(null);
EFTestContext db = new EFTestContext();
Post[] posts = db.Posts.ToArray(); // Error here
}
If I remove the navigation property public virtual Post MainPostEntity everything works as expected. However, when I add it, I get:
base {System.SystemException} = {"The ForeignKeyAttribute on property 'MainPostEntity' on type 'EFTest.Blog' is not valid. The foreign key name 'MainPostId' was not found on the dependent type 'EFTest.Post'. The Name value should be a comma separated list of foreign key property names."}
If I remove the fluent API call, I get {"Invalid column name 'Blog_Id'."}
If I change the attribute from [ForeignKey("MainPostId")] to [ForeignKey("Id")] I get the following error {"Invalid column name 'Blog_Id'."}
What am I doing wrong?
How do I enable the navigation property from Blog to the Main Post?
The problem you are having is that you're creating two relationships between the same two tables and EF can't distinguish which relationship the navigation property BlogEntity is part of. Using the fluent api you can explicitly tell it so, the data annotations are then not needed.
modelBuilder.Entity<Blog>().HasMany(b => b.PostEntities).
WithRequired(p => p.BlogEntity).
HasForeignKey(p => p.BlogId).
WillCascadeOnDelete(true);
modelBuilder.Entity<Blog>().HasOptional(b => b.MainPostEntity).
WithMany().
HasForeignKey(b => b.MainPostId).
WillCascadeOnDelete(false);

EF6 code first multiple 1-to-many mapping issue / "Multiplicity" error

I am receiving the following error when attempting to create the database:
One or more validation errors were detected during model generation:
Interaction_CauseElement_Source: : Multiplicity is not valid in Role
'Interaction_CauseElement_Source' in relationship
'Interaction_CauseElement'. Because the Dependent Role properties are
not the key properties, the upper bound of the multiplicity of the
Dependent Role must be '*'.
Interaction_EffectElement_Source: : Multiplicity is not valid in Role
'Interaction_EffectElement_Source' in relationship
'Interaction_EffectElement'. Because the Dependent Role properties are
not the key properties, the upper bound of the multiplicity of the
Dependent Role must be '*'.
I've seen this error in other Stack Overflow posts, but in the examples I found, the OP was trying for a 1-to-1 relationship in both directions between the tables. That is not what I am looking for.
Here is my model:
public class Element
{
[Key]
public int ID { get; set; }
[Required, MaxLength(64)]
public string Name { get; set; }
[MaxLength(200)]
public string Description { get; set; }
}
public class Interaction
{
[Key]
public int ID { get; set; }
[Index, Required]
public int CauseID { get; set; }
[Index, Required]
public int EffectID { get; set; }
[MaxLength(64)]
public string Location { get; set; }
[ForeignKey("CauseID")]
public virtual Element CauseElement { get; set; }
[ForeignKey("EffectID")]
public virtual Element EffectElement { get; set; }
}
Items in the Elements table are unique. A pair of elements can interact with each other in any number of locations. The CauseID/EffectID pair is not going to be unique.
The only other place I am changing the model is in the OnModelCreating method. I had received this error:
Introducing FOREIGN KEY constraint
'FK_dbo.Interactions_dbo.Elements_Cause' on table
'Interactions' may cause cycles or multiple cascade paths.
Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
FOREIGN KEY constraints. Could not create constraint. See previous
errors.
And had to create a cascade policy for the model. This code fixed that error:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Prevent cyclic cascade on elements table
modelBuilder.Entity<Interaction>()
.HasRequired(i => i.CauseElement)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Interaction>()
.HasRequired(i => i.EffectElement)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
But then I received the cryptic "Multiplicity" error. It seems like it wants me to make public virtual Element CauseElement into a collection like public virtual ICollection<Element> CauseElement, but that would not properly model the relationship.
I found the solution. This article on EntityFrameworkTutoral.net helped out. Because I need TWO references from the Interaction class to the Element class, this relationship is too complex to model in EF with only the attributes.
I had to update the model and then use the fluent API to tell EF how to treat the relationships. I updated my model to the following:
public class Element
{
public Element()
{
CauseElements = new List<Interaction>();
EffectElements = new List<Interaction>();
}
[Key]
public int ID { get; set; }
[Required, MaxLength(64)]
public string Name { get; set; }
#region Navigation
public virtual ICollection<Interaction> CauseElements { get; set; }
public virtual ICollection<Interaction> EffectElements { get; set; }
#endregion
}
public class Interaction
{
[Key]
public int ID { get; set; }
[Index]
public int CauseID { get; set; }
[Index]
public int EffectID { get; set; }
[MaxLength(64)]
public string Location { get; set; }
#region Navigation
[ForeignKey("CauseID")]
public virtual Element CauseElement { get; set; }
[ForeignKey("EffectID")]
public virtual Element EffectElement { get; set; }
#endregion
}
And in my DbContext class I used the fluent API to create the link between the Interaction.CauseElement and Element.CauseElements and which property was the foreign key for the Interaction table (and the same with the Effect relationship):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Prevent cyclic cascade on elements table
modelBuilder.Entity<Interaction>()
.HasRequired(i => i.CauseElement)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Interaction>()
.HasRequired(i => i.EffectElement)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
//Create the links between the element, the key, and the collection
modelBuilder.Entity<Interaction>()
.HasRequired<Element>(i => i.CauseElement)
.WithMany(e => e.CauseElements)
.HasForeignKey(i => i.CauseID);
modelBuilder.Entity<Interaction>()
.HasRequired<Element>(i => i.EffectElement)
.WithMany(e => e.EffectElements)
.HasForeignKey(i => i.EffectID);
base.OnModelCreating(modelBuilder);
}
It seems that Entity Framework tries to automatically infer the relationships between the tables when you have a simple 1-to-many relationship. If I removed EffectElement from the Interaction class (and EffectElements from Element), EF was able to create the relationship easily. But when I added it back, I received the error again.
Since that Element type showed up twice in the Interaction class, it didn't know how to create the relationship. I had to explicitly define it in the OnModelCreating method.
You reversed the responsibilities of the "ForeignKey" attribute. It goes on the ID field, specifying the property for which it serves as the foreign key. You want something as below:
// To-One on Element
[ForeignKey("Element")]
public int ElementId { get; set; }
public virtual Element Element { get; set; }
Also, this is actually a one-to-one relationship. A one-to-many relationship in this case would be:
// To-Many on Element
public virtual ICollection<Element> Elements{ get; set; }

Relationship troubles with Entity Framework

I need help creating the relationship in entity framework as everything I have tried gives me errors when trying to add the migration or if I get passed that then I try to update the database and get an error about indexes with the same name.
public class Profile
{
public Profile()
{
Environments = new HashSet<Environment>();
}
[Key]
public int Id { get; set; }
public string VersionCreated { get; set; }
public string DiskLocation { get; set; }
public string Name { get; set; }
public DateTime DateTime { get; set; }
public virtual Product Product { get; set; }
public virtual Instance OriginalInstance { get; set; }
public virtual ICollection<Environment> Environments { get; set; }
}
public class Instance
{
public Instance()
{
TestResults = new HashSet<TestResult>();
Environments = new HashSet<Environment>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public string UserFriendlyName { get; set; }
public virtual Product Product { get; set; }
public virtual Profile LastKnownProfile { get; set; }
public virtual Computer Computer { get; set; }
public virtual ICollection<TestResult> TestResults { get; set; }
public virtual ICollection<Environment> Environments { get; set; }
}
The problem with the above classes is that the OrginalInstance property on the Profile class and the LastKnownProfile in the Instance class are supposed to just be foreign keys to those specific tables and they probably won't be the same very often. They can also both possibly be null.
I have tried:
modelBuilder.Entity<Instance>().HasRequired(i => i.LastKnownProfile);
modelBuilder.Entity<Profile>().HasRequired(p => p.OriginalInstance);
This gave me an Unable to determine the principal end of an association between the types 'EcuWeb.Data.Entities.Instance' and 'EcuWeb.Data.Entities.Profile'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations. error.
and with:
modelBuilder.Entity<Instance>().HasRequired(i => i.LastKnownProfile).WithOptional();
modelBuilder.Entity<Profile>().HasRequired(p => p.OriginalInstance).WithOptional();
The database adds a foreign key reference back to itself.
...that the OrginalInstance property on the Profile class and the
LastKnownProfile in the Instance class are supposed to just be foreign
keys to those specific tables and they probably won't be the same very
often. They can also both possibly be null.
In this case you actually want two one-to-many relationships between Profile and Instance if I don't misunderstand your quote above. It would mean that many Profiles can have the same OriginalInstance and that many Instances can have the same LastKnownProfile. The correct mapping would look like this then:
modelBuilder.Entity<Profile>()
.HasOptional(p => p.OriginalInstance)
.WithMany()
.Map(m => m.MapKey("OriginalInstanceId"));
modelBuilder.Entity<Instance>()
.HasOptional(i => i.LastKnownProfile)
.WithMany()
.Map(m => m.MapKey("LastKnownProfileId"));
The lines with MapKey are optional. Without them EF will create a foreign key with a default name.
Also note that you must use HasOptional (instead of HasRequired) if "both can possibly be null".

Categories