I have an object which can optionally have a reference to a next and/or previous record. Something like this:
public class Foo
{
[Key]
public int Id {get; set;}
[ForeignKey("Previous")]
public int? PreviousId {get; set;}
public Foo Previous {get; set;}
[InverseProperty("Previous")]
public Foo Next {get; set;}
}
Unfortunately this does not work, instead resulting in the error message Unable to determine the principal end of an association between the types Foo and Foo.
The idea is that by setting the PreviousId, the Previous Foo will get its Next set automatically by EF. This is to prevent errors caused by Next and Previous getting out of sync. Also note that PreviousId can be null, in which case no record in the database should have a Next pointing at that record. Is there any way to implement this?
I've managed to achieve what you wanted by using fluent api aproach. I needed to remove PreiousId property from Foo class - it will be added later on by mapping.
public class Foo
{
[Key]
public virtual int Id { get; set; }
public virtual Foo Previous { get; set; }
public virtual Foo Next { get; set; }
}
Change as well all your properties to virtual as this will allow ef to dynamically track state of the properties in the memory. Then inside DbContext derived class you need to override OnModelCreating method and define mapping there:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>()
.HasOptional(f => f.Next)
.WithOptionalPrincipal(f => f.Previous)
.Map(c => c.MapKey("PreviousId"));
base.OnModelCreating(modelBuilder);
}
This will add to Foo table PreviousId column which will be the foreign key of the relationship. It will define 1-0 relationship. If you assign one Foo entity to another's Previous property then assigned entity will have reference to it in Next property. I tested it with the following code:
using(MyDbContext context = new MyDbContext("Test"))
{
context.Database.Delete();
Foo foo1 = context.Foos.Create();
Foo foo2 = context.Foos.Create();
foo1.Next = foo2;
context.Foos.Add(foo1);
context.Foos.Add(foo2);
context.SaveChanges();
}
using (MyDbContext context = new MyDbContext("Test"))
{
Foo foo1 = context.Foos.OrderBy(f => f.Id).First();
Foo foo2 = context.Foos.OrderBy(f => f.Id).Skip(1).First();
// foo1.Next == foo2 and foo2.Previous == foo1
}
For those out there using entity framework core, this is what I wound up doing
public class LinkedListNode
{
public int Id { get; set; }
public int? NextId { get; set; }
public virtual LinkedListNode Next { get; set; }
public int? PrevId { get; set; }
public virtual LinkedListNode Prev { get; set; }
public long SortOrder { get; set; }
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<LinkedListNode>()
.HasOne<LinkedListNode>(x => x.Next)
.WithMany()
.HasPrincipalKey("Id")
.HasForeignKey("NextId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired(false);
builder.Entity<LinkedListNode>()
.HasOne<LinkedListNode>(x => x.Prev)
.WithMany()
.HasPrincipalKey("Id")
.HasForeignKey("PrevId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired(false);
}
Related
I am having the data model as follows.
class KnowledgeDocument
{
public int? Id {get; set;}
public virtual ICollection<KDValueCreation> KDValueCreations { get; set; }
}
class KDValueCreation
{
public int? Id{get; set;}
public int? KDReferenceId { get; set; }
public virtual KnowledgeDocument KDReference { get; set; }
public int KnowledgeDocumentId { get; set; }
public virtual KnowledgeDocument KnowledgeDocument { get; set; }
public decimal Amount {get; set;}
}
Now, when I am trying to create a new KnowledgeDocument along with KDValueCreations as follows.
KnowledgeDocument kd = new KnowledgeDocument();
kd.KDValueCreations.Add(new KDValueCreation{ Amount = "500000"});
When I save the kd, kd is saved without any issue and in KDValueCreation, 1 record is created and both KDReferenceId and KnowledgeDocumentId are populated with the same kdId. But, I want to populate only KnowledgeDocumentId and stop KDReferenceId from populating and set it to null.
As both the fields are pointing to the same reference, Entity framework is populating the Id on both the fields.
How can I achieve this still by saving the KnowledgeDocument with its children?
Please suggest. Thanks in advance.
As I can see, the reason is in two identical relationships. You need to specify what properties are related. You can do it by InverseProperty attribute or by FluentAPI like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// configures one-to-many relationship
modelBuilder.Entity<KDValueCreation>()
.HasRequired<KnowledgeDocument>(c => c.KnowledgeDocument)
.WithMany(d => d.KDValueCreations)
.HasForeignKey(c => c.KnowledgeDocumentId);
}
}
or this:
modelBuilder.Entity<KnowledgeDocument>()
.HasMany<KDValueCreation>(d => d.KDValueCreations)
.WithRequired(c => c.KnowledgeDocument)
.HasForeignKey(c => c.KnowledgeDocumentId);
I am trying to create one-to-many and reverse one-to-one relationship using code first. Here is what I ma trying to do
1) One-to-Many between two classes and it works as expected.
public class X
{
[Key]
public int XId { get; set; }
public ICollection<Y> Y { get; set; }
}
public class Y
{
[Key]
public int YId { get; set; }
public int XId { get; set; }
public X X { get; set; }
}
public class DataContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Y>()
.HasRequired(y => y.X)
.WithMany(x => x.Y)
.HasForeignKey(y => y.XId);
}
}
Now what I want to do is to create Reverse One-to-One optional relationship between Y and X, such that the X will contain a foreign key of Y...How is it possible? Here is what I am trying to do and it throws some Multiplicity Error
public class X
{
[Key]
public int XId { get; set; }
public ICollection<Y> Y { get; set; }
public int YId {get; set; }
[ForiegnKey("YId")]
public Y YOptional { get; set; }
}
public class Y
{
[Key]
public int YId { get; set; }
public int XId { get; set; }
public X X { get; set; }
public X XOptional {get; set; }
}
public class DataContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Y>()
.HasRequired(y => y.X)
.WithMany(x => x.Y)
.HasForeignKey(y => y.XId);
modelBuilder.Entity<X>()
.HasOptional(x => x.YOptional)
.WithOptionalDependent(y=> y.XOptional);
}
}
You can't have a relationship between two entities that is defined differently from either end. So you can't do 1:* from one direction and 1:1 from another.
Let me make a guess that you don't really want it to be 1:1 from the dependent end. From that end it will always only point to one thing.
In mappings, unlike in life, unless you have many to many, a child only has one parent.
You can, however, create a 0..1 : * relationaship (zero or one to many). Where the parent can have one or more children (e.g. "many") but the child can exist without a parent, but it can never have more than one parent (e.g. "zero or one").
Here is the simplest method of making your classes result in a [zero or one] to many relationship. Notice that I made the foreign key in the class Y a nullable int. WIth this setup, EF conventions will result in a mapping that lets a child exist without a parent.
public class X
{
[Key]
public int XId { get; set; }
public ICollection<Y> Y { get; set; }
}
public class Y
{
[Key]
public int YId { get; set; }
public int? XId { get; set; }
public X X { get; set; }
}
public class DataContext : DbContext
{
public DbSet<X> XSet { get; set; }
public DbSet<Y> YSet { get; set; }
}
Here is a screenshot of visual model derived from the above classes and context.
I think this achieves the behavior you are seeking if my guess that you may just be perceiving it differently is correct.
Using the actual class names you mentioned in the comments:
Mapping a User that can have many Singles is not a problem. However, when you want to map a 1:1 association between a User and a Single you have to choose which of the two is the "principle" entity. You can't have a foreign key column in both tables because one entity will always be inserted before the other one. The "dependent" entity is inserted next, and it refers to the principal's primary key value.
So if User is the principal entity, you could have a class model similar to this:
public class User
{
public User()
{
this.Singles = new HashSet<Single>();
}
public int UserId { get; set; }
public string Name { get; set; }
public Single Single { get; set; }
public virtual ICollection<Single> Singles { get; set; }
}
public class Single
{
public int SingleId { get; set; }
public string Name { get; set; }
public virtual User User { get; set; }
public int SuperUserId { get; set; }
public User SuperUser { get; set; }
}
And two options for mappings:
Option 1: User as principal
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(u => u.Singles)
.WithRequired(s => s.SuperUser).HasForeignKey(s => s.SuperUserId);
modelBuilder.Entity<User>().HasOptional(s => s.Single)
.WithOptionalPrincipal(s => s.User).Map(m => m.MapKey("UserId"));
}
In the data model, Single now has two foreign keys, UserId and SuperUserId. This is how to create a User and a Single in User.Single and User.Singles:
var superUser = new User { Name = "superUser1" };
var single = new Single { Name = "single" };
superUser.Singles.Add(single);
db.Users.Add(superUser);
superUser.Single = single;
db.SaveChanges();
And EF will first insert the User, then the Single having both foreign keys equal to the User's primary key.
Option 2: Single as principle
You can also make Single the principal entity in the 1:1 association:
modelBuilder.Entity<User>().HasOptional(s => s.Single)
.WithOptionalDependent(s => s.User).Map(m => m.MapKey("SingleId"));
Now there's only one foreign key in Single (SuperUserId) and a foreign key in User (SingleId). If you execute the same code, now EF will throw
Unable to determine a valid ordering for dependent operations.
This is because there is a chicken-and-egg problem: the Single must be created before the dependent User can be created, but the User must be created before the Single can be added to its Singles collection. This could be solved by assigning the Single later:
var superUser = new User { Name = "superUser1" };
var single = new Single { Name = "single" };
superUser.Singles.Add(single);
db.Users.Add(superUser);
db.SaveChanges();
superUser.Single = single;
db.SaveChanges();
You'd want to wrap this in a TransactionScope, so I think this option is less viable.
Note
As you see, in a 1:1 mapping the foreign key can't be mapped to a property in the class model. There is no HasForeignKey in the fluent API after WithOptionalDependent or WithOptionalPrincipal. Also, this association can only be mapped by the fluent API. In data annotations there is not attribute to indicate the principal end of an association.
I'm a gibbering wreck trying to get EF code first to let me do something that I could do in 2 minutes in SQL. Had I not already spent 5 days trying to get it to work, I'd just code up my database in DDL and use ADO.NET. But I digress...
I want to have 2 tables, where each record in A has a corresponding record in B. They're both part of the same object; they need to be in separate tables for reasons I won't go into (but they really do, so don't go there). If I were designing it from the database end, I'd simply have an FK relationship from B to A. Job done.
In EF Code First, I've tried using both the shared primary key method and the one-to-one foreign key association method, and neither work for me. I've also tried 100 or so combinations of all the variants I can think of, and I'm no further forward.
As I said, all I want is there to be a navigable relationship from A to B (and back would be nice, but I've read that's not possible), and for that relationship to be lazy-loaded, so that I can say a.b and have access to the fields of b.
I can't possibly enumerate all the things I've tried, so let me just give an example of what nearly works:
class Foo
{
public int Id { get; set; }
public string FooProperty { get; set; }
public virtual Bar Bar { get; set; }
}
class Bar
{
public int Id { get; set; }
public string BarProperty { get; set; }
}
Note that there's no back-reference from Bar to Foo, since (a) SQL Server would complain about multiple cascade delete paths, and (b) EF would complain about not knowing which side is the principal end of the association. So... fine - I can live without it.
What this gets me in the database is a Foos table with Id, FooProperty and Bar_Id fields, and a Bars table with Id and BarProperty fields. That's pretty close to they way I'd model it in SQL, although I'd probably put the FK field in Bar rather than Foo. But since it's 1:1 it doesn't really matter, I guess.
The reason I say that this nearly works is that if I add a Bar and associated Foo and then load them back in, the Bar property of the Foo object is null.
using (var dbContext = new MyDbContext())
{
var foo = dbContext.Foos.Create();
foo.FooProperty = "Hello";
dbContext.Foos.Add(foo);
var bar = dbContext.Bars.Create();
bar.BarProperty = "world";
foo.Bar = bar;
dbContext.SaveChanges();
}
using (var dbContext = new MyDbContext())
{
foreach (var foo in dbContext.Foos)
Console.WriteLine(foo.Bar.Id); // BOOM! foo.Bar is null
}
I would normally expect the evaluation of foo.Bar to trigger lazy-loading of the Bar object, but it doesn't - that property remains null.
How can I fix it?
Thsi should work:
Context
public class FoobarCtx : DbContext
{
public DbSet<Bar> Bars { get; set; }
public DbSet<Foo> Foos { get; set; }
public FoobarCtx()
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Bar>()
.HasRequired(f => f.Foo)
.WithRequiredDependent(b => b.Bar)
.Map(x => x.MapKey("FooId"))
.WillCascadeOnDelete(true);
}
}
Entities
public class Foo
{
public int Id { get; set; }
public string Foo1 { get; set; }
public string Foo2 { get; set; }
public virtual Bar Bar { get; set; }
}
public class Bar
{
public int Id { get; set; }
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public virtual Foo Foo { get; set; }
}
I tested it in EF 4.3, but I think it should work also in EF5. The Key is the OnModelCreating method. There you can define either one or the other as the principal/descendant and get rid of the Microsoft SQL restriction.
For more information see this blog-post. For more information about the model builder (fluent API), go here.
To enable lazy loading, use the DbContext.FooSet.Create() method. Example here.
As a reminder to myself, if nothing else...
LueTm arrived at a solution that produced the table structure I originally had in mind (with a FooId column in the Bar table), and independent PKs on the two tables. It was still not possible to access the Foo.Bar property without first loading it using dbContext.Foos.Include(f => f.Bar).
I was also able to get things to work pretty well with a shared primary key (both tables have a PK, but only the one in Foos is an identity (auto-increment) column, and there's an FK relationship from the Id in Bars to the Id in Foos.
To do this, I had a Bar property in the Foo class, and a Foo property in the Bar class (so 2-way navigation works), and put the following in my OnModelCreating.
modelBuilder.Entity<Bar>()
.HasRequired(x => x.Foo)
.WithRequiredDependent(x => x.Bar)
.WillCascadeOnDelete(true);
modelBuilder.Entity<Foo>()
.HasRequired(x => x.Bar)
.WithRequiredPrincipal(x => x.Foo)
.WillCascadeOnDelete(true);
(I'm not sure that the second call here actually does anything).
But again, you still need the Include() call in order to be able to access foo.Bar.
I just went through this myself. I have a FoodEntry, with a Food, and the Food has a FoodGroup.
public class FoodEntry
{
public int Id { get; set; }
public string User { get; set; }
public Food Food { get; set; }
public decimal PortionSize { get; set; }
public Portion Portion { get; set; }
public int Calories { get; set; }
public Meal Meal { get; set; }
public DateTime? TimeAte { get; set; }
public DateTime EntryDate { get; set; }
}
public class Food
{
public int Id { get; set; }
public string Name { get; set; }
public FoodGroup FoodGroup { get; set; }
}
public class FoodGroup
{
public int Id { get; set; }
public string Name { get; set; }
}
I'm using code first and my POCO classes are defined just as yours are. I do not have the properties marked virtual.
In any event, the database generates as I would expect - with foreign keys as you described.
But this query resulted in just getting the FoodEntry collection with nulls in the Food, Portion and Meal properties:
var foodEntries = db.FoodEntries
.Where(e => e.User == User.Identity.Name).ToList();
I changed the query to this, and the entire graph loaded for my collection:
var foodEntries = db.FoodEntries
.Include( p => p.Food)
.Include(p => p.Food.FoodGroup)
.Include(p => p.Portion)
.Include( p => p.Meal)
.Where(e => e.User == User.Identity.Name).ToList()
;
For a 1:1 relationship in addition to a 1:many relationship (Foo has several Bars and also a CurrentBar):
modelBuilder.Entity<Foo>()
.HasOptional(f => f.CurrentBar)
.WithMany()
.HasForeignKey(f => f.CurrentBarId);
modelBuilder.Entity<Bar>()
.HasRequired(b => b.Foo)
.WithMany(f => f.Bars)
.HasForeignKey(b => b.FooId);
From what I understand on several posts the TPT architecure, with EF, does not create the necessary ON DELETE CASCADE when using a shared primary key.... It was also said that the EF context will handle the proper order of deletion of the sub-classed tables (however I do get an error that it breaks the constraint and that I can fix it with adding the ON DELETE CASCADE on the sub-class table)...
more background info...
I have a Section class, which has a number, title, and a list of pages. The page is designed using a super class which holds basic page properties. I have about 10+ sub-classes of the page class. The Section class holds an ICollection of these pages. The DB is created properly with the exception of no ON DELETE CASCADE on the sub-classed tables.
My code will create the entities and adds to the DB fine. However, if I try to delete a section (or all sections) it fails todelete due to the FK constraint on my sub-class page table...
public abstract BaseContent
{
... common properties which are Ignored in the DB ...
}
public class Course : BaseContent
{
public int Id {get;set;}
public string Name {get;set;}
public string Descripiton {get;set;}
public virtual ICollection<Chapter> Chapters{get;set;}
...
}
public class Chapter : BaseContent
{
public int Id {get;set;}
public int Number {get;set;}
public string Title {get;set;}
public virtual Course MyCourse{get;set;}
public virtual ICollection<Section> Sections{get;set;}
...
}
public class Section : BaseContent
{
public int Id {get;set;}
public int Number {get;set;}
public string Title {get;set;}
public virtual Chapter MyChapter {get;set;}
public virtual ICollection<BasePage> Pages {get;set;}
...
}
public abstract class BasePage : BaseContent, IComparable
{
public int Id { get; set; }
public string Title { get; set; }
public string PageImageRef { get; set; }
public ePageImageLocation ImageLocationOnPage { get; set; }
public int PageNumber { get; set; }
public virtual Section MySection { get; set; }
...
}
public class ChapterPage : BasePage
{
public virtual int ChapterNumber { get; set; }
public virtual string ChapterTitle { get; set; }
public virtual string AudioRef { get; set; }
}
public class SectionPage : BasePage
{
public virtual int SectionNumber { get; set; }
public virtual string SectionTitle { get; set; }
public virtual string SectionIntroduction { get; set; }
}
... plus about 8 other BasePage sub-classes...
public class MyContext: DbContext
{
...
public DbSet<Course> Courses { get; set; }
public DbSet<Chapter> Chapters { get; set; }
public DbSet<Section> Sections { get; set; }
public DbSet<BasePage> Pages { get; set; }
...
}
.. Fluent API ... (note Schema is defined to "" for SqlServer, for Oracle its the schema name)
private EntityTypeConfiguration<T> configureTablePerType<T>(string tableName) where T : BaseContent
{
var config = new EntityTypeConfiguration<T>();
config.ToTable(tableName, Schema);
// This adds the appropriate Ignore calls on config for the base class BaseContent
DataAccessUtilityClass.IgnoreAllBaseContentProperties<T>(config);
return config;
}
public virtual EntityTypeConfiguration<BasePage> ConfigurePageContent()
{
var config = configureTablePerType<BasePage>("PageContent");
config.HasKey(pg => pg.Id);
config.HasRequired(pg => pg.Title);
config.HasOptional(pg => pg.PageImageRef);
config.Ignore(pg => pg.ImageLocationOnPage);
return config;
}
public virtual EntityTypeConfiguration<ChapterPage> ConfigureChapterPage()
{
var config = configureTablePerType<ChapterPage>("ChapterPage");
config.HasOptional(pg => pg.AudioRef);
config.Ignore(pg => pg.ChapterNumber);
config.Ignore(pg => pg.ChapterTitle);
return config;
}
public virtual EntityTypeConfiguration<SectionPage> ConfigureSectionPage()
{
var config = configureTablePerType<SectionPage>("SectionPage");
config.HasOptional(pg => pg.AudioRef);
config.Ignore(pg => pg.SectionNumber);
config.Ignore(pg => pg.SectionTitle);
return config;
}
... other code to model other tables...
So the app is able to populate content and the relationships are properly set up. However, when I try to delete the course, I get the error that the delete failed due to the constraint on the ChapterPage to PageContent table..
Here is the code which deletes the Course (actually I delete all courses)...
using (MyContext ctx = new MyContext())
{
ctx.Courses.ToList().ForEach(crs => ctx.Courses.Remove(crs));
AttachLookupEntities(ctx);
ctx.SaveChanges();
}
If I add the 'ON DELETE CASCADE' in the ChapterPage and SectionPage table for its shared primary with PageContent, the delete goes through.
In summary,
The only solution that I have seen is to manually alter the constraints to add the ON DELETE CASCADE for all of my sub-class page tables. I can implement the change, as I have code which generates the DB script for the EF tables I need (a small subset of our whole DB) since we will not use EF to create or instantiate the DB (since it does not properly support migrations as yet...).
I sincerely hope that I have miscoded something, or forgot some setting in the model builder logic. Because if not, the EF designers have defined an architecure (TPT design approach) which cannot be used in any real world situation without a hack workaround. It's a half finished solution. Do not get me wrong, I like the work that has been done, and like most MSFT solutions its works for 70% of most basic application usages. It just is not ready for more complex situations.
I was trying to keep the DB design all within the EF fluent API and self-contained. It's about 98% there for me, just would be nice if they finished the job, maybe in the next release. At least it saves me all the CRUD operations.
Ciao!
Jim Shaw
I have reproduced the problem with a little bit simpler example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
namespace EFTPT
{
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<BasePage> Pages { get; set; }
}
public abstract class BasePage
{
public int Id { get; set; }
public string Name { get; set; }
public Parent Parent { get; set; }
}
public class DerivedPage : BasePage
{
public string DerivedName { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<BasePage> BasePages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>()
.HasMany(p => p.Pages)
.WithRequired(p => p.Parent); // creates casc. delete in DB
modelBuilder.Entity<BasePage>()
.ToTable("BasePages");
modelBuilder.Entity<DerivedPage>()
.ToTable("DerivedPages");
}
}
class Program
{
static void Main(string[] args)
{
using (var ctx = new MyContext())
{
var parent = new Parent { Pages = new List<BasePage>() };
var derivedPage = new DerivedPage();
parent.Pages.Add(derivedPage);
ctx.Parents.Add(parent);
ctx.SaveChanges();
}
using (var ctx = new MyContext())
{
var parent = ctx.Parents.FirstOrDefault();
ctx.Parents.Remove(parent);
ctx.SaveChanges(); // exception here
}
}
}
}
This gives the same exception that you had too. Only solutions seem to be:
Either setup cascading delete for the TPT constraint in the DB manually, as you already tested (or put an appropriate SQL command into the Seed method).
Or load the entites which are involved in the TPT inheritance into memory. In my example code:
var parent = ctx.Parents.Include(p => p.Pages).FirstOrDefault();
When the entities are loaded into the context, EF creates actually two DELETE statements - one for the base table and one for the derived table. In your case, this is a terrible solution because you had to load a much more complex object graph before you can get the TPT entities.
Even more problematic is if Parent has an ICollection<DerivedPage> (and the inverse Parent property is in DerivedPage then):
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<DerivedPage> Pages { get; set; }
}
public abstract class BasePage
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DerivedPage : BasePage
{
public string DerivedName { get; set; }
public Parent Parent { get; set; }
}
The example code wouldn't throw an exception but instead delete the row from the derived table but not from the base table, leaving a phantom row which cannot represent an entity anymore because BasePage is abstract. This problem is not solvable by a cascading delete but you were actually forced to load the collection into the context before you can delete the parent to avoid such a nonsense in the database.
A similar question and analysis was here: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/3c27d761-4d0a-4704-85f3-8566fa37d14e/
I'm working to solve a very tedious problem.
I have a class called Nation and a class called NationAlly
public class Nation
{
public int ID {get; set;}
public int name {get;set;}
public List<NationAlly> NationAllies {get;set;}
}
public class NationAlly
{
public int ID {get; set;}
public int level {get;set;}
public Nation toNation {get;set;}
}
I'm using EF 4 and CodeFirst with a DbContext called NationsDB to manage my database on SQL Server 2008.
If I create a new object of type Nation and I try to call nationsDB.SaveChanges, I got the following exception:
"Multiplicity constraint violated. The role 'NationAlly_toNation_Target' of the relationship 'CodeFirstNamespace.NationAlly_toNation' has multiplicity 1 or 0..1."
I tried to save a Nation with NationAllies field null and this exception is not thrown, the nation table in the database gets all the correct values.
In my database the table Nation has 2 fields: ID(primary key), name
The table NationAlly has 3 fields: ID(primary key), level, NationID
The two tables are linked with a relationship where NationAlly.NationID is foreign key and Nation.ID is primary key.
Isn't strange? In my eyes the table NationAlly should have a field called NationID1 and another called NationID2 to create the "relationship" between a nation and a list of other nations.
What did I do wrong?
You are perhaps a victim of the EF Code-First mapping conventions which create automatically a relationship between NationAllies and toNation you don't want to have.
If I understand you correctly (but I am not 100 percent sure, if I do), you actually want to have two relationships and you have exposed only one end of the relationship in each of the entities. So, NationAllies does NOT point to toNation but to an "invisible" Owner nation in your NationAlly entity.
If that is the case you need to explicitly overwrite the convention mappings. In the Fluent API of EF 4.1 this could look like:
public class MyContext : DbContext
{
public DbSet<Nation> Nations { get; set; }
public DbSet<NationAlly> NationAllies { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Nation>()
.HasMany(n => n.NationAllies)
.WithRequired()
.Map(conf => conf.MapKey("OwnerID"))
.WillCascadeOnDelete(false);
modelBuilder.Entity<NationAlly>()
.HasRequired(a => a.toNation)
.WithMany()
.Map(conf => conf.MapKey("NationID"))
.WillCascadeOnDelete(false);
}
}
This mapping would create the two foreign keys OwnerID and NationID in the NationAllies table, both pointing to the primary key ID in the Nations table.
Edit
Here is the application I have tested with:
Create a new Console App in VS2010 / .NET 4.0, name it "NationsApp"
Add a reference to "EntityFramework.dll"
Clear the content of "Program.cs" and paste instead the following in:
Content of Program.cs:
using System;
using System.Collections.Generic;
using System.Data.Entity;
namespace NationsApp
{
public class Nation
{
public int ID { get; set; }
public int name { get; set; }
public List<NationAlly> NationAllies { get; set; }
}
public class NationAlly
{
public int ID { get; set; }
public int level { get; set; }
public Nation toNation { get; set; }
}
public class NationsContext : DbContext
{
public DbSet<Nation> Nations { get; set; }
public DbSet<NationAlly> NationAllies { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Nation>()
.HasMany(n => n.NationAllies)
.WithRequired()
.Map(conf => conf.MapKey("OwnerID"))
.WillCascadeOnDelete(false);
modelBuilder.Entity<NationAlly>()
.HasRequired(a => a.toNation)
.WithMany()
.Map(conf => conf.MapKey("NationID"))
.WillCascadeOnDelete(false);
}
}
class Program
{
static void Main(string[] args)
{
using (var context = new NationsContext())
{
try
{
// We have three Nations and two Allies
Nation nation1 = new Nation() {
NationAllies = new List<NationAlly>() };
Nation nation2 = new Nation() {
NationAllies = new List<NationAlly>() };
Nation nation3 = new Nation() {
NationAllies = new List<NationAlly>() };
NationAlly ally1 = new NationAlly();
NationAlly ally2 = new NationAlly();
// Nation1 has two Allies
// (Nation1 is the "owner" of both Allies)
nation1.NationAllies.Add(ally1);
nation1.NationAllies.Add(ally2);
// toNation of ally1 refers to Nation2
ally1.toNation = nation2;
// toNation of ally2 refers to Nation3
ally2.toNation = nation3;
context.Nations.Add(nation1);
context.Nations.Add(nation2);
context.Nations.Add(nation3);
context.SaveChanges();
}
catch (Exception e)
{
throw;
}
}
}
}
}
You can set a breakpoint on "throw" to watch possible exceptions in e in the debugger.
This creates a database called NationsApp.NationsContext if you are using SQL Server Express and don't have any further connection strings defined.
It gives two relationships Nation_NationAllies (FK is "OwnerID") and NationAlly_toNation (FK is "NationID"). All columns are non-nullable. The result in the DB is the following:
In case this helps someone getting this error... I was getting this message while doing queries rather than saving to the database. My data design:
public class Base {
public int Id {get; set;}
}
public class Child {
[Key][ForeignKey("Base")] public int Id {get; set;}
public virtual Base Base {get; set;}
public Child() {
Base = new Base();
}
}
The problem was in the constructor. Turns out EF4.1 doesn't like when you initialize associations there! I removed that constructor and things started working again.