EF Two-to-Many relationship - asp.net-core

I have a Section object that is in relationship with exactly two Node objects. Basically, the Section object is a route with a starting point and an ending point. I can't find a lot about Multiple-to-Many relationships and I don't even know if this is a thing.
public class Section
{
public Guid Id { get; set; }
public int Length { get; set; }
public Node StartNode { get; set; }
public Guid StartNodeId { get; set; }
public Node EndNode { get; set; }
public Guid EndNodeId { get; set; }
}
public class Node
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Section> Sections { get; set; }
}
This should not work :
modelBuilder.Entity<Section>()
.HasOne(se => se.StartNode)
.WithMany(sn => en.Sections)
.HasForeignKey(se => se.StartNodeId);
modelBuilder.Entity<Section>()
.HasOne(se => se.EndNode)
.WithMany(en => en.Sections)
.HasForeignKey(se => se.EndNodeId);
Should I map this as a Many-to-Many relationship ? I would like to have access to the Sections from a Node, and the two points from my Section.

What you actually wanting is multiple one-to-many with the same entity.
So your Node class should be as follows:
public class Node
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Section> StarNodeSections { get; set; }
public ICollection<Section> EndNodeSections { get; set; }
}
Then in the Fluent API configuration as follows:
modelBuilder.Entity<Section>()
.HasOne(se => se.StartNode)
.WithMany(sn => sn.StarNodeSections) // <-- Here it is
.HasForeignKey(se => se.StartNodeId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Section>()
.HasOne(se => se.EndNode)
.WithMany(en => en.EndNodeSections) // <-- Here it is
.HasForeignKey(se => se.EndNodeId)
.OnDelete(DeleteBehavior.Restrict);

Related

EF Core 2.2, owned entities generated as another table when multiple in hierarchy

I have a model with a class Address marked [Owned] and a hierarchy of people (person, customer or employee, then even more subtypes etc). There are addresses at different stages of this hierarchy and all of it ends up in one table as EF Core is limited to table per hierarchy. I expected all the attributes from address to appear multiple times in that person table (once per mention in any of the subtypes) however it doesn't appear at all! Instead i see FK for each of them and a separate Address table.
Does EF Core not support multiple owned members of the same type? If not is there anything i should do? I don't have any fluent API / specific configuration that could interfere with the defaults (new empty console project, only config line is .UseSQLServer(connectionstring)
Sample code bellow :
public class SampleContext : DbContext
{
public virtual DbSet<Address> Addresses { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Person> Persons { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("my connection string here");
}
base.OnConfiguring(optionsBuilder);
}
}
[Owned]
public class Address
{
public int Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string City { get; set; }
}
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class Employee : Person
{
public Address Address { get; set; }
}
public class Customer : Person
{
public Address DeliveryAddress { get; set; }
public Address InvoicingAddress { get; set; }
}
Expected Person table :
DeliveryAddressAddressLine1
DeliveryAddressAddressLine2
DeliveryAddressAddressLine3
DeliveryAddressAddressCity
InvoicingAddressAddressLine1
InvoicingAddressAddressLine2
InvoicingAddressAddressLine3
InvoicingAddressAddressCity
EmployeeAddressAddressLine1
EmployeeAddressAddressLine2
EmployeeAddressAddressLine3
EmployeeAddressAddressCity
Generated Person table (+ an unexpected Address table):
EmployeeAddressAddressId
DeliveryAddressAddressId
InvoicingAddressAddressId
Edit : updated the question, added the context definition and noticed i had Addresses as a DbSet so i assume this may be the cause, removing it gives me the following error :
Cannot use table 'Person' for entity type 'Customer.DeliveryAddress#Address' since it is being used for entity type 'Employee.Address#Address' and there is no relationship between their primary keys.`
According to EF Core Owned Entity Types documentation:
Inheritance hierarchies that include owned entity types are not supported
You can overcome this problem by moving public Address Address { get; set; }, public Address DeliveryAddress { get; set; } and public Address InvoicingAddress { get; set; } navigation properties from Employee and Customer to the base class Person as follows:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public Address Address { get; set; }
public Address DeliveryAddress { get; set; }
public Address InvoicingAddress { get; set; }
}
Then configure with fluent API to override the Navigation_OwnedEntityProperty rule for owned entity column name as follows:
modelBuilder.Entity<Person>().OwnsOne(p => p.Address,
a =>
{
a.Property(p => p.AddressLine1).HasColumnName("EmployeeAddressLine1");
a.Property(p => p.AddressLine2).HasColumnName("EmployeeAddressLine2");
a.Property(p => p.AddressLine2).HasColumnName("EmployeeAddressLine3");
a.Property(p => p.City).HasColumnName("EmployeeAddressCity");
}).OwnsOne(p => p.DeliveryAddress,
a =>
{
a.Property(p => p.AddressLine1).HasColumnName("DeliveryAddressLine1");
a.Property(p => p.AddressLine2).HasColumnName("DeliveryAddressLine2");
a.Property(p => p.AddressLine2).HasColumnName("DeliveryAddressLine3");
a.Property(p => p.City).HasColumnName("DeliveryAddressCity");
}).OwnsOne(p => p.InvoicingAddress,
a =>
{
a.Property(p => p.AddressLine1).HasColumnName("InvoicingAddressLine1");
a.Property(p => p.AddressLine2).HasColumnName("InvoicingAddressLine2");
a.Property(p => p.AddressLine2).HasColumnName("InvoicingAddressLine3");
a.Property(p => p.City).HasColumnName("InvoicingAddressCity");
});
Now you if you don't want to move public Address Address { get; set; }, public Address DeliveryAddress { get; set; } and public Address InvoicingAddress { get; set; } navigation properties from Employee and Customer to the base class Person then you have to create separate tables from each address types as follows:
modelBuilder.Entity<Employee>().OwnsOne(p => p.Address,
a =>
{
a.ToTable("EmployeeAddresses");
});
modelBuilder.Entity<Customer>().OwnsOne(p => p.DeliveryAddress,
a =>
{
a.ToTable("DeliveryAddresses");
}).OwnsOne(p => p.InvoicingAddress,
a =>
{
a.ToTable("InvoicingAddresses");
});

Self Referencing Many-to-Many relations

I have an Ticket entity:
public class Ticket
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Relation> RelatedTickets { get; set; }
}
I want to setup many-to-many self-relations in Entity Framework Core, so i made two one-to-many relations:
public class Relation
{
[Required, ForeignKey("TicketFrom")]
public int FromId { get; set; }
[Required, ForeignKey("TicketTo")]
public int ToId { get; set; }
public virtual Ticket TicketFrom { get; set; }
public virtual Ticket TicketTo { get; set; }
}
I've tried to create the relationship using fluent API:
builder.Entity<Relation>()
.HasKey(uc => new { uc.FromId, uc.ToId });
builder.Entity<Relation>()
.HasOne(c => c.TicketFrom)
.WithMany(p => p.RelatedTickets)
.HasForeignKey(pc => pc.FromId);
builder.Entity<Relation>()
.HasOne(c => c.TicketTo)
.WithMany(p => p.RelatedTickets)
.HasForeignKey(pc => pc.ToId);
But in result i have an error:
Cannot create a relationship between 'Ticket.RelatedTickets' and
'Relation.TicketTo', because there already is a relationship between
'Ticket.RelatedTickets' and 'Relation.TicketForm'. Navigation
properties can only participate in a single relationship.
The possible solution is to add Parent relation directly to TicketEntity:
public class Ticket
{
public int Id { get; set; }
[Required, ForeignKey("ParentRelation")]
public Nullable<int> ParentRelationId { get; set; }
public virtual Ticket ParentRelation {get;set;}
public virtual ICollection<Ticket> RelatedTickets { get; set; }
...
}
With fluent api like this:
modelBuilder.Entity<Ticket> =>
{
entity
.HasMany(e => e.RelatedTickets)
.WithOne(e => e.ParentRelation)
.HasForeignKey(e => e.ParentRelationId );
});
But it looks 'dirty' to store parent relation like this.
What is the right approach?
It's not possible to have just one collection with relations. You need two - one with relations the ticket equals TicketFrom and second with relations the ticket equals TicketTo.
Something like this:
Model:
public class Ticket
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Relation> RelatedTo { get; set; }
public virtual ICollection<Relation> RelatedFrom { get; set; }
}
public class Relation
{
public int FromId { get; set; }
public int ToId { get; set; }
public virtual Ticket TicketFrom { get; set; }
public virtual Ticket TicketTo { get; set; }
}
Configuration:
modelBuilder.Entity<Relation>()
.HasKey(e => new { e.FromId, e.ToId });
modelBuilder.Entity<Relation>()
.HasOne(e => e.TicketFrom)
.WithMany(e => e.RelatedTo)
.HasForeignKey(e => e.FromId);
modelBuilder.Entity<Relation>()
.HasOne(e => e.TicketTo)
.WithMany(e => e.RelatedFrom)
.HasForeignKey(e => e.ToId);
Note that a solution using Parent is not equivalent, because it would create one-to-many association, while if I understand correctly you are seeking for many-to-many.
Here is very good explanation how to make many-to-many relationship in EF Core
Many-to-many self referencing relationship
Every collection or reference navigation property can only be a part of a single relationship. While many to many relationship with explicit join entity is implemented with two one to many relationships. The join entity contains two reference navigation properties, but the main entity has only single collection navigation property, which has to be associated with one of them, but not with both.
builder.Entity<Relation>()
.HasKey(uc => new { uc.FromId, uc.ToId });
builder.Entity<Relation>()
.HasOne(c => c.TicketFrom)
.WithMany() // <-- one of this must be empty
.HasForeignKey(pc => pc.FromId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<Relation>()
.HasOne(c => c.TicketTo)
.WithMany(p => p.RelatedTickets)
.HasForeignKey(pc => pc.ToId);
Just make sure that WithMany exactly matches the presence/absence of the corresponding navigation property.
Note that you have to turn the delete cascade off.
#IvanStoev is correct. This is an example of a more general self referencing many to many relationship with many parents and many children.
public class Ticket
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public List<TicketTicket> TicketChildren { get; set; }
public List<TicketTicket> TicketParents { get; set; }
}
public class TicketTicket
{
public int TicketChildId { get; set; }
public Ticket TicketChild { get; set; }
public int TicketParentId { get; set; }
public Ticket TicketParent { get; set; }
}
modelBuilder.Entity<TicketTicket>()
.HasKey(tt => new {tt.TicketChildId, tt.TicketParentId});
modelBuilder.Entity<Ticket>()
.HasMany(t => t.TicketChildren)
.WithOne(tt => tt.ProductParent)
.HasForeignKey(f => tt.ProductParentId);
modelBuilder.Entity<Ticket>()
.HasMany(t => t.TicketParents)
.WithOne(tt => tt.TicketChild)
.HasForeignKey(tt => tt.TicketChildId);

Parent Child Relationship in ASP.NET MVC 4

I am trying to do this:
Hibernate: Parent-Child Relationship to Itself
but in ASP.NET MVC 4
here are my 2 models (which i have no clue if this is the correct way to do this):
public class Group
{
public int GroupID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public virtual ICollection<GroupRelation> GroupRelations { get; set; }
}
public class GroupRelation
{
public int GroupRelationID { get; set; }
public int? ParentID { get; set; }
public int? ChildID { get; set; }
[ForeignKey("ParentID")]
public virtual Group ParentGroups { get; set; }
[ForeignKey("ChildID")]
public virtual Group ChildGroups { get; set; }
}
Here is my Context(again no clue if this is right):
public class TaskTrackerContext : DbContext
{
public DbSet<Group> Groups { get; set; }
public DbSet<GroupRelation> GroupRelations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Group>()
.HasMany(g => g.GroupRelations).WithOptional(g => g.ChildGroups).HasForeignKey(g => g.ChildID);
modelBuilder.Entity<Group>()
.HasMany(g => g.GroupRelations).WithOptional(g => g.ParentGroups).HasForeignKey(g => g.ParentID);
}
}
With this setup i get the following in my database:
(i tried to put in a pic or a link to a pic and it wont let me...)
So it makes the 2 relationships i am expecting "PK_GroupID - FK_ParentID" and "PK_GroupID - FK_ChildID", but then it creates an extra column called "Group_GroupID" and makes the following relationship: "PK_GroupID - FK_Group_GroupID".
So what am I doing wrong?

How to use composite Ids in one-to-many mappings in fluent nhibernate?

I got a scenario where a composite Id uniquely identifies an entity. I defined the MSSQL to have a multiple primary key on those fields. In addition I would like an auto-incremented id to be used for referencing a one-to-many relationship. Here's the schema:
public class Character
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Region Region { get; set; }
public virtual string Realm { get; set; }
public virtual IList<CharProgression> Progression { get; set; }
}
public class CharProgression
{
public virtual int Id { get; set; }
public virtual Character Character { get; set; }
public virtual Stage Stage { get; set; }
public virtual int ProgressionPoints { get; set; }
public virtual int NumOfSaves { get; set; }
}
public class Stage
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}
The mappings look like this:
class CharacterMap : ClassMap<Character>
{
public CharacterMap()
{
Table("characters");
Id(ch => ch.Id, "id").GeneratedBy.Identity().Not.Nullable();
CompositeId().KeyProperty(ch => ch.Region, "region")
.KeyProperty(ch => ch.Realm, "realm")
.KeyProperty(ch => ch.Name, "name");
HasMany<CharProgression>(ch => ch.Progression).Inverse().Cascade.All();
}
}
class CharProgressionMap : ClassMap<CharProgression>
{
public CharProgressionMap()
{
Table("char_progression");
CompositeId().KeyReference(cprog => cprog.Character, "char_id",
.KeyReference(cprog => cprog.Stage, "stage_id");
Id(cprog => cprog.Id, "id").GeneratedBy.Identity().Not.Nullable();
Map(cprog => cprog.ProgressionPoints, "progression_points");
Map(cprog => cprog.NumOfSaves, "num_of_saves");
}
}
public class StageMap : ClassMap<Stage>
{
public StageMap()
{
Table("stages");
Id(st => st.Id, "id").GeneratedBy.Identity().Not.Nullable();
Map(st => st.Name, "name");
Map(st => st.Description, "description");
}
}
Now, the thing is that I would like to use SaveOrUpdate() on a character and use the composite id for the update, since the character uniqueness is defined by those 3 fields - region, realm, name.
However, when I am referencing the Character from CharProgression, I don't want to use the composite Id as I don't want the char_progression table to hold 3 fields for identifying a character, a simple Id is enough... which is why I also defined an IDENTITY id on the Character entity.
Is what i'm trying possible? or is there another way to achieve this?
Thanks :)

Nhibernate Mapping relationships on multiple columns

I'm having problems mapping a relationaship between two entities when there are two columns involved in the mapping.
I'm modelling a state machine with two object types - State and Transition. Each process has its own state machine, so States and Transitions need to be identified by ProcessId. My entity classes are like this:
public class State
{
public virtual long Id { get; set; }
public virtual int ProcessId { get; set; }
public virtual int Ordinal { get; set; }
public virtual Process Process { get; set; }
public virtual ICollection<Transition> TransitionsIn { get; set; }
public virtual ICollection<Transition> TransitionsOut { get; set; }
}
public class Transition
{
public virtual long Id { get; set; }
public virtual long ProcessId { get; set; }
public virtual int FromStateNum { get; set; }
public virtual int ToStateNum { get; set; }
public virtual long StateActionId { get; set; }
public virtual Process Process { get; set; }
public virtual StateAction StateAction { get; set; }
public virtual State FromState { get; set; }
public virtual State ToState { get; set; }
}
I need the navigation properties (State.TransitionsIn, State.TransitionsOut, Transition.FromState, Transition.ToState) to be based on the ProcessId and the Ordinal number of the state. For example, Transition.FromState should navigate to the entity where t.ProcessId = s.ProcessId and t.FromStateNum = s.Ordinal.
I've tried the following mapping, but it complains that I'm using two columns to map to one (StateId).
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(x => x.Id);
HasMany(s => s.TransitionsIn)
.KeyColumns.Add("ProcessId", "ToStateNum")
.Inverse();
HasMany(s => s.TransitionsOut)
.KeyColumns.Add("ProcessId", "FromStateNum")
.Inverse();
}
}
public class TransitionMap : ClassMap<Transition>
{
public TransitionMap()
{
Id(x => x.Id);
References(t => t.FromState)
.Columns("ProcessId", "Ordinal");
References(t => t.ToState)
.Columns("ProcessId", "Ordinal");
}
}
How can I get this to work?
How about this mapping.. I have not tested it but just trying to give a direction.
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(x => x.Id);
HasMany(s => s.TransitionsIn)
.KeyColumn("ProcessId")
.KeyColumn("ToStateNum").PropertyRef("Ordinal")
.Inverse();
HasMany(s => s.TransitionsOut)
.KeyColumn("ProcessId")
.KeyColumn("FromStateNum").PropertyRef("Ordinal")
.Inverse();
}
}
public class TransitionMap : ClassMap<Transition>
{
public TransitionMap()
{
Id(x => x.Id);
References(t => t.FromState)
.Columns("ProcessId", "FromStateNum");
References(t => t.ToState)
.Columns("ProcessId", "ToStateNum");
}
}