Can I avoid the foreign key properties in my entity? - entity-framework

I have the following classes:
public class Bicycle
{
public int BicycleId { get; set; }
public DateTime YearOfManufacture { get; set; }
public int BicycleManufactuerId { get; set; }
public BicycleManufacturer BicycleManufacturer { get; set; }
}
public class BicycleManufacturer
{
public int BicycleManufacturerId { get; set; }
public string Description { get; set; }
}
Each Bicycle must have a BicycleManufacturer (1:1). There could be some BicycleManufacturer that isn't associate with any Bicycle. Most will be associated with multiple Bicycle entities.
I have the following fluent API code to set up the FK relationship:
modelBuilder.Entity<Bicycle>()
.HasRequired(a => a.BicycleManufacturer)
.WithMany()
.HasForeignKey(u => u.BicycleManufactuerId);
This all seems to work fine. However, I would really like to remove the BicycleManufacturerId property from the Bicycle entity. It's only there to establish the FK relationship. Is there a way I can create the proper FK relationship if I remove this property?

You can remove the property and use the mapping:
modelBuilder.Entity<Bicycle>()
.HasRequired(a => a.BicycleManufacturer)
.WithMany()
.Map(m => m.MapKey("BicycleManufactuerId"));

You can also do it by convention by adding the relationship on the other side as a collection.
public class Bicycle
{
public int BicycleId { get; set; }
public DateTime YearOfManufacture { get; set; }
public int BicycleManufactuerId { get; set; }
public BicycleManufacturer BicycleManufacturer { get; set; }
}
public class BicycleManufacturer
{
public int BicycleManufacturerId { get; set; }
public ICollection<Bicycle> Bicycles { get; set; }
public string Description { get; set; }
}

Related

Why do my one to many relationships in subclasses get a cycle error?

I want to have a one-to-many relation between subclasses of one master class,
and in second step use of master class for relationships with other class
please see below models:
BasePost.cs
public abstract class BasePost
{
[Key]
public long Id { get; set; }
public ICollection<Comment> Comments { get; set; }
}
Question.cs:
public class Question: BasePost
{
[Required] public string Title { get; set; }
public string Body { get; set; }
public ICollection<Answer> Answers { get; set; }
}
Answer.cs
public class Answer: BasePost
{
public string Body { get; set; }
public int Vote { get; set; }
public Question Question { get; set; }
public long QuestionId { get; set; }
}
Comment.cs
public class Comment
{
[Key]
public long Id { get; set; }
public string Text { get; set; }
public BasePost BasePost { get; set; }
public long BasePostId { get; set; }
public DateTime CreateDate { get; set; }
}
and finally in ApplicationDbContext.cs :
builder.Entity<Answer>()
.HasOne(x => x.Question)
.WithMany(a => a.Answers)
.HasForeignKey(k => k.QuestionId)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<Comment>()
.HasOne(x => x.BasePost)
.WithMany(a => a.Comments)
.HasForeignKey(k => k.BasePostId)
.OnDelete(DeleteBehavior.ClientSetNull);
but after migration and update database I get below error:
Introducing FOREIGN KEY constraint 'FK_BasePosts_BasePosts_QuestionId' on table 'BasePosts' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

EF Core More Navigation properties from two tables

I am trying to create navigation properties for two table.
Here is the code.
public class CourseMaster
{
public int Id { get; set; }
public string Name { get; set; }
public int? TeamLeaderId { get; set; }
[ForeignKey("TeamLeaderId")]
public StudentMaster TeamLeader { get; set; }
public int? GroupLeaderId { get; set; }
[ForeignKey("GroupLeaderId")]
public StudentMaster GroupLeader { get; set; }
public virtual ICollection<StudentMaster> Students { get; set; }
}
public class StudentMaster
{
public int id { get; set; }
public string Name { get; set; }
public int FirstSemCourseId { get; set; }
[ForeignKey("FirstSemCourseId")]
public CourseMaster FirstSemCourse { get; set; }
public int SecondSemCourseId { get; set; }
[ForeignKey("SecondSemCourseId")]
public CourseMaster SecondSemCourse { get; set; }
public int ThirdSemCourseId { get; set; }
[ForeignKey("ThirdSemCourseId")]
public CourseMaster ThirdSemCourse { get; set; }
public int CourseMasterId { get; set; }
public CourseMaster Course { get; set; }
}
// Fluent API
modelBuilder.Entity<StudentMaster>()
.HasOne(p => p.Course)
.WithMany(b => b.Students)
.HasForeignKey(p => p.CourseMasterId);
But when i am creating migrations i am getting following error.
Unable to determine the relationship represented by navigation property 'CourseMaster.TeamLeader' of the type 'StudentMaster'. Either manually configure the relationship, or ignore this property from model.
Whether the procedure i am following is right or should i create intermediate class.
or how should i create class.
Any help are appreciated.
Thanks

EF issues with 2 foreign keys going to same table

Using the new ASP.NET Core and Entity Framework 7.0 RC1 Final. I have two fields with a one-to-many relationship between Standards and Students. If I just have the one FK and Navigation Key the code works just fine, but when I add in the second FK (Standard2) and Nav field (Students2) I get the following error message:
InvalidOperationException: The navigation 'Students' on entity type 'TestProject.Models.Standard' has not been added to the model, or ignored, or target entityType ignored.
public class Standard
{
public Standard()
{
}
public int StandardId { get; set; }
public string StandardName { get; set; }
public IList<Student> Students { get; set; }
public IList<Student> Students2 { get; set; }
}
public Student()
{
}
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }
//Foreign key for Standard
public int StandardId { get; set; }
public int StandardId2 { get; set; }
[ForeignKey("StandardId")]
public Standard Standard { get; set; }
[ForeignKey("StandardId2")]
public Standard Standard2 { get; set; }
}
How do I have two FK's to the same table in EF 7?
The problem is that you need to specify the other end of your relationships by using InverseProperty attribute, something that EF cannot infer on its own and hence throws an exception:
public class Standard
{
public int StandardId { get; set; }
public string StandardName { get; set; }
[InverseProperty("Standard")]
public IList<Student> Students { get; set; }
[InverseProperty("Standard2")]
public IList<Student> Students2 { get; set; }
}
Or you can achieve the same results by using fluent API:
modelBuilder.Entity<Standard>()
.HasMany(s => s.Students)
.WithOne(s => s.Standard)
.HasForeignKey(s => s.StandardId);
modelBuilder.Entity<Standard>()
.HasMany(s => s.Students2)
.WithOne(s => s.Standard2)
.HasForeignKey(s => s.StandardId2);

Entity Framework Code first creates unexpected Tables and Relationships

Using EntityFramework 6.1.3, I've got the following
public class RacesContext:DbContext
{
public DbSet<Race> Races { get; set; }
public DbSet<Sailboat> Sailboats { get; set; }
public DbSet<VenueParticipation> VenueParticipations { get; set; }
}
public class Crew
{
public int CrewId { get; set; }
public string Name { get; set; }
}
public class Sailboat
{
[Key]
public int SailboatId { get; set; }
public string Name { get; set; }
public string Skipper { get; set; }
public virtual ICollection<Crew> BoatCrew { get; set; }
}
public class VenueParticipation
{
[Key]
public int Id { get; set; }
public virtual ICollection<Sailboat> Boats { get; set; }
public virtual ICollection<Race> Races { get; set; }
}
public class Race
{
[Key]
public int RaceId { get; set; }
public string Venue { get; set; }
public DateTime Occurs { get; set; }
}
EF creates the Creates the Crews table with the proper PK and FK as I would expect. But creates the Races Sailboats, VenueParticipations tables in an unexpected way. Sailboats get's the expected PK but the unexpected FK VenueParticipation_Id as does Races. I was expecting the VenueParticipations table to get FKs to the others allowing a many to many relationship.. I'm sure I'm missing something here. Any advice would be great.
You can either configure the joining tables VenueParticipationSailboat, VenueParticipationRace with the proper FKs or you can use the fluent API:
modelBuilder.Entity<VenueParticipation>()
.HasMany(t => t.Sailboats)
.WithMany(t => t.VenueParticipations)
.Map(m =>
{
m.ToTable("VenueParticipationSailboat");
m.MapLeftKey("VenueParticipationID");
m.MapRightKey("SailboatID");
});
https://msdn.microsoft.com/en-us/data/jj591620.aspx#ManyToMany

Code First Foreign Key Configuration

I am having difficulty maintaining multiple relationships between a parent class and it's children. Can anyone tell me why I can create two child references in the parent but not a third? The code below only works when the third reference is commented out.
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public int Child1Id { get; set; }
public Child Child1 { get; set; }
public int Child2Id { get; set; }
public Child Child2 { get; set; }
//public int Child3Id { get; set; }
public Child Child3 { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public Parent Parent { get; set; }
}
public class CFContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithRequiredPrincipal(p => p.Child1)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithRequiredPrincipal(p => p.Child2)
.WillCascadeOnDelete(false);
//modelBuilder.Entity<Child>()
// .HasRequired(c => c.Parent)
// .WithRequiredPrincipal(p => p.Child3)
// .WillCascadeOnDelete(false);
}
}
It looks like you are trying to make a one-to-many relation from Parent to Child entity. In that case the code should look like this:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public Parent Parent { get; set; }
}
You don't have to specify the relation in Fluent API as long as you are following the default conventions regarding naming of the navigation properties and foreign key. You will have to use Fluent API and/or attributes to configure relations of you use non-convention names, eg renaming ParentId some something else requires you to mark it with at [ForeignKey("Parent")] attribute.
The most common use case for using Fluent API is for disabling cascade delete (there is no way to do this with attributes).