Fluent API - collection navigation - entity-framework

I am working with asp.net mvc with durandal & breeze templates.
I have the following classes (removed some properties for clarity):
public class Rolling
{
[Key]
public int Id { get; set; }
...
public virtual List<Itinerary> Itineraries { get; set; }
}
public class Itinerary
{
[Key]
public int Id { get; set; }
...
public int? VehicleId { get; set; }
public int? TrailerId { get; set; }
...
public virtual Rolling Vehicle { get; set; }
public virtual Rolling Trailer { get; set; }
}
I have the following fluent API:
modelBuilder.Entity<Rolling>()
.HasMany(c => c.Itineraries)
.WithOptional(c => c.Vehicle)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Rolling>()
.HasMany(c => c.Itineraries)
.WithOptional(c => c.Trailer)
.WillCascadeOnDelete(false);
Please note the order of declaring these fluent APIs.
At runtime, I perform a breeze query client side to get all the rolling entities:
var query = entityQuery.from('Rollings')
.where(predicates)
.orderBy(orderyByClause)
.expand('Itineraries');
For each one, I check the itineraries collection property:
rollings()[0].itineraries
I noted that I only retrieved itineraries for rollings where the Trailer property of Itinerary is filled. None of the rollings where the Vehicle property of Itinerary is filled.
BUT if I swap fluent API like this:
modelBuilder.Entity<Rolling>()
.HasMany(c => c.Itineraries)
.WithOptional(c => c.Trailer)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Rolling>()
.HasMany(c => c.Itineraries)
.WithOptional(c => c.Vehicle)
.WillCascadeOnDelete(false);
Then I noted that I only retrieved itineraries for rollings where the Vehicle property of Itinerary is filled. None of the rollings where the Trailer property of Itinerary is filled.
Is this a normal behaviour? A bug?
Thanks for investigating.

It looks like this is a follow up question for Navigation property no more working after migration of breeze 1.4.2.
I was able to verify the behavior you described.
I also verified that this is the EF behavior by running the query on the server:
var rolling = mgr.Context.Rollings.Include("Itineraries").First();
var itineraries = mgr.Context.Itineraries.Local;
You will notice that itineraries will only have Itineraries with either Vehicle or Trailer filled (depending on the fluent API order of definitions).
It looks like a bug to me, but an Entity Framework bug (not Breeze's bug).
I think Microsoft will have a better saying in this, so posted your question at http://social.msdn.microsoft.com/Forums/en-US/7438371d-1072-4a9a-aab8-d12842493066/possible-bug-include-not-working-properly.

Related

Entity Framework cascade delete configuration

here are two entities of my model with fluent entityframework configuration of it
Player.cs
public class Player
{
public string Name { get; set; }
public virtual Statistics Statistics { get; set; }
}
Statistics.cs
public class Statistics
{
public int GamePlayed { get; set; }
public int Assists { get; set; }
public int Goals { get; set; }
}
DbContextClass
modelBuilder.Entity<Player>()
.HasOptional(x => x.Statistics)
.WithMany()
.Map(x => x.MapKey("StatisticsId"));
In the end, a foreignKey named 'StatisticsId' is create on my Player Table which is ok. I want on a player deletion, to cascadeDelete related stats. Here's my problem, adding WillCascadeDelete to my statement as
modelBuilder.Entity<Player>()
.HasOptional(x => x.Statistics)
.WithMany()
.Map(x => x.MapKey("StatisticsId"))
.WillCascadeOnDelete(true);
results as deleting the player when statistics are deleted. How could I make this work the opposite way by keeping StatisticsId foreignKey on the player table ?
The main point here is that Statistics can 'live alone' without any Player related. Is it possible to set Entity Framework to auto delete related Statistics or this has to be done manually ?
I assume you just need to add WillCascadeOnDelete to Statistics :
modelBuilder.Entity<Statistics>()
.WillCascadeOnDelete(true);
I haven't tested though.

EF Many to Many: A has many B's, B doesn't need to know

Say I have the following. Note that Category doesn't need to have a reference to the projects it's associated with. Is there a way to configure this, or does convention dictate that I should be throwing a collection of Projects in my Category model?
public class Project
{
public Guid Id { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
public Guid Id { get; set; }
}
There are a few similar questions around but the answers don't seem to address it.
Update:
As I thought, I do need to have that intermediate table, but EF does it for me by following Moho's answer.
Use Fluent API:
modelBuilder.Entity<Project>()
.HasMany( p => p.Categories )
.WithMany();
This is possible using Fluent api:
modelBuilder.Entity<Project>()
.HasMany(p => p.Categories)
.WithMany()
.Map(m =>
{
m.MapLeftKey("Id");
m.MapRightKey("Id");
m.ToTable("ProjectsCategories");
});

Entity Framework Code First - Navigation property on Composite Primaty Key

Firebird 2.5
Entity Framework 5
FirebirdClientDll 3.0.0.0
Hi, I'm trying to access my legacy database with the Entity Framework (Code First).
I got the problem that the database does not use foreign keys...
public class CUSTOMERS
{
public int CUSTOMERID { get; set; }
public string NAME{ get; set; }
}
public class INVOICES
{
public int INVOICEID{ get; set; }
public int CUSTOMERID{ get; set; }
public virtual CUSTOMERS CUSTOMERS { get; set; }
}
public class INVOICEContext : DbContext
{
public DbSet<CUSTOMERS> CUSTOMERS{ get; set; }
public DbSet<INVOICES> INVOICES{ get; set; }
public INVOICEContext(DbConnection connectionString) : base(connectionString, false)
{
Database.SetInitializer<INVOICEContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
/*modelBuilder.Entity<INVOICES>().HasRequired(b => b.CUSTOMERS)
.WithMany()
.Map(p => p.MapKey("INVOICEID"));*/ //Doesn't work because INVOICEID is defined
modelBuilder.Entity<INVOICES>().HasKey(a => new { a.INVOICEID, a.CUSTOMERID});
modelBuilder.Entity<CUSTOMERS>().HasKey(a => new { a.CUSTOMERID });
base.OnModelCreating(modelBuilder);
}
}
Normally I could remove the property CUSTOMERID from the class INVOICES, but in this case it is part of the primary key...
I found many threads which suggested to use IsIndependent, but it seems to be removed from the Entity Framework 5 (or 4.1).
I hope you can understand my poor English and maybe give me a hint what I'm doing wrong ^^
I don't know what you mean with "the database does not use foreign keys". So, maybe the following is not the answer you are looking for. But I'd say that you can use your relationship mapping that is commented out in your code if you replace ...MapKey... by HasForeignKey and use CUSTOMERID instead of INVOICEID as the foreign key property:
modelBuilder.Entity<INVOICES>()
.HasRequired(b => b.CUSTOMERS)
.WithMany()
.HasForeignKey(b => b.CUSTOMERID);
The model and the rest of the mapping is fine in my opinion. Your relationship is an identifying relationship (that means that the foreign key is part of a composite primary key) which is a valid mapping with Entity Framework.
Try this ...
modelBuilder.Entity<INVOICES>()
.HasRequired(i => i.CUSTOMERS)
.WithMany()
.HasForeignKey(i => i.CUSTOMERID);

EF 4.1 Code First ModelBuilder HasForeignKey for One to One Relationships

Very simply I am using Entity Framework 4.1 code first and I would like to replace my [ForeignKey(..)] attributes with fluent calls on modelBuilder instead. Something similar to WithRequired(..) and HasForeignKey(..) below which tie an explicit foreign key property (CreatedBySessionId) together with the associated navigation property (CreatedBySession). But I would like to do this for a one to one relationsip instead of a one to many:
modelBuilder.Entity<..>().HasMany(..).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId)
A more concrete example is below. This works quite happily with the [ForeignKey(..)] attribute but I'd like to do away with it and configure it purely on modelbuilder.
public class VendorApplication
{
public int VendorApplicationId { get; set; }
public int CreatedBySessionId { get; set; }
public virtual Session CreatedBySession { get; set; }
}
public class Session
{
public int SessionId { get; set; }
[ForeignKey("CurrentApplication")]
public int? CurrentApplicationId { get; set; }
public virtual VendorApplication CurrentApplication { get; set; }
public virtual ICollection<VendorApplication> Applications { get; set; }
}
public class MyDataContext: DbContext
{
public IDbSet<VendorApplication> Applications { get; set; }
public IDbSet<Session> Sessions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Session>().HasMany(x => x.Applications).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId).WillCascadeOnDelete(false);
// Note: We have to turn off Cascade delete on Session <-> VendorApplication relationship so that SQL doesn't complain about cyclic cascading deletes
}
}
Here a Session can be responsible for creating many VendorApplications (Session.Applications), but a Session is working on at most one VendorApplication at a time (Session.CurrentApplication). I would like to tie the CurrentApplicationId property with the CurrentApplication navigation property in modelBuilder instead of via the [ForeignKey(..)] attribute.
Things I've Tried
When you remove the [ForeignKey(..)] attribute the CurrentApplication property generates a CurrentApplication_VendorApplicationId column in the database which is not tied to the CurrentApplicationId column.
I've tried explicitly mapping the relationship using the CurrentApplicationId column name as below, but obviously this generates an error because the database column name "CurrentApplicationId" is already being used by the property Session.CurrentApplicationId:
modelBuilder.Entity<Session>().HasOptional(x => x.CurrentApplication).WithOptionalDependent().Map(config => config.MapKey("CurrentApplicationId"));
It feels like I'm missing something very obvious here since all I want to do is perform the same operation that [ForeignKey(..)] does but within the model builder. Or is it a case that this is bad practise and was explicitly left out?
You need to map the relationship as one-to-many and omit the collection property in the relationship.
modelBuilder.Entity<Session>()
.HasOptional(x => x.CurrentApplication)
.WithMany()
.HasForeignKey(x => x.CurrentApplicationId)

EF Many-To-Many on single entity

I have an issue to implement many-to-many relationship with same entities. Here's my class:
public class District
{
[Key]
public int DistrictId { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Abbreviation { get; set; }
public List<District> SubDistricts { get; set; }
}
My goal is to have all districts within same table, and to have them correlated, many districts to many districts.
If I don't specify mappings, EF Code First acts as if it is one-to-many relationship.
I've tried to give directions to model builder, but it's not working:
modelBuilder.Entity<District>()
.HasMany(d => d.SubDistricts)
.WithMany(d => d.SubDistricts)
.Map(mc => { mc.ToTable("DistrictLinks", "dbo");
mc.MapLeftKey("ParentId");
mc.MapRightKey("ChildId");
});
Is there any way to do this with WF? Thanks in advance!
You must use the WithMany overload which doesn't take a parameter:
modelBuilder.Entity<District>()
.HasMany(d => d.SubDistricts)
.WithMany()
.Map(mc => { mc.ToTable("DistrictLinks", "dbo");
mc.MapLeftKey("ParentId");
mc.MapRightKey("ChildId");
});
It is not possible that the same navigation property is start and end of an association at the same time. They either must be different or the end is "unvisible" and not exposed in the model - which is the case in your model.
Your solution works well, thank you! In the meanwhile, I've came up with another way to resolve issue. Basically I've created two navigational properties in class:
public List<District> ChildDistricts { get; set; }
public List<District> ParentDistricts { get; set; }
so my mapping looks like this now:
modelBuilder.Entity<District>()
.HasMany(d => d.ParentDistricts)
.WithMany(d => d.ChildDistricts)
.Map(mc => { mc.ToTable("DistrictLinks", "dbo");
mc.MapLeftKey("ParentId");
mc.MapRightKey("ChildId");
});
As a result, I get exactly the same kind of table in SQL Server, but I believe I can navigate better like this. I actually forgot to mention that hierarchy is of importance here as well, not just links between districts.
Thank you once again :)