Entity Framework 6 One-Way relationship using Code First - entity-framework

I have the following scenario:
Color Class
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
public string Hex
{
get;
set;
}
Widget Class
public int ID
{
get;
set;
}
public int HeaderBackgroundColorID
{
get;
set;
}
public Color HeaderBackgroundColor
{
get;
set;
}
Using Code-First, I am trying to create a one-way relationship between Widget to Color classes with the HeaderBackgroundColor / HeaderBackgroundColorID Fields.
normally i would do this in the config class:
this.HasOptional(r => r.HeaderBackgroundColor )
.WithMany(m => m.Widgets)
.HasForeignKey(fk => fk.HeaderBackgroundColorID);
but i am not intrested in adding a Widgets collection to the Color class.
tried this:
this.HasOptional(r => r.HeaderBackgroundColor )
.WithMany()
.HasForeignKey(fk => fk.HeaderBackgroundColorID);
but that throws a validation error.
What's the way to do this right?

You are getting an error because HeaderBackgroundColorId is a non-nullable int, so it cannot be optional.
All you need to do to achieve what you're looking for is to turn the foreign key into a nullable int...
public int? HeaderBackgroundColorID { get; set; }
Because you named the foreign key to match the navigation property (HeadBackgroundColorId and HeaderBackgroundColor) which follows Code First conventions, you do not need to create any explicit mappings. Simply making the above change will make the relationship optional.

Related

EF Core 2 duplicate column created with foreign key relationship

I'm trying add migration using EF core 2 code first method. The issue is that, the entities with foreign key relationship are created with a foreign key id suffixed with '1' at the end and a redundant column with the same name but without the 1 at the end which is not a foreign key.
Examples are my 2 classes, Store and StoreVisit as shown below:
Store
[Table("Store")]
public class Store
{
public Store()
{
StoreVisits = new HashSet<StoreVisit>();
}
[Key]
public int StoreId { get; set; }
[StringLength(30)]
public string ShopName { get; set; }
[StringLength(50)]
public string ShopKeeper { get; set; }
public string ContactNo { get; set; }
[StringLength(70)]
public string Address { get; set; }
[StringLength(20)]
public string Street { get; set; }
[StringLength(50)]
public string City { get; set; }
public IEnumerable<StoreVisit> StoreVisits { get; set; }
}
Store Visit
[Table("StoreVisit")]
public class StoreVisit
{
[Key]
public int StoreVisitId { get; set; }
[StringLength(50)]
public string Location { get; set; }
[StringLength(50)]
public string Notes { get; set; }
[DataType(DataType.Time)]
public DateTime StartTime { get; set; }
[DataType(DataType.Time)]
public DateTime EndTime { get; set; }
public Store Store { get; set; }
}
The Visit class is created in the database with the column shown in the image below:
As you can see, the StoreVisit table has columns "StoreId1" which is the actual foreign key and "StoreId" which is not a foreign key.
I have even configured the relationship with Fluent API as below:
modelBuilder.Entity<Store>()
.HasMany(c => c.StoreVisits)
.WithOne(e => e.Store)
.IsRequired();
Can someone help.
Note that Entity Framework Core is smart enough to detect relationships among your classes which will be turned into database tables with relationships if you use its conventions. So this is redundant to use annotations like [Key] above StoreId property.
Second thing, As an advice, try to use simple and clean names for classes or properties as they can be potentially similar to those automatically created by EF. For example, in your case I prefer to avoid using store inside StoreVisit class name again (e.g in case of many to many relationship, derived table is named StoreVisit like one that you employed just without 's', Although your case is one to many),
And Final tip is the reason for appearing redundant StoreId column. Actually, In your case, this is not necessary to use Fluent API as EF can detect the relationship. In addition, you've written wrong configuration for modelBuilder. So remove it and let EF to generate it (unless you plan to have fully defined relationship to consume its advantages in your code).
The StoreId is one that you told EF to generate it (as required)
in modelBuilder.
The StoreId1 is EF Auto generated column (Foreign Key) based on one
to many relationship. '1' is appended in order to avoid column name duplication.
A foreign key needs to be defined on the class.
[Table("StoreVisit")]
public class StoreVisit
{
[Key]
public int StoreVisitId { get; set; }
public int StoreId { get; set; }
[StringLength(50)]
public string Location { get; set; }
[StringLength(50)]
public string Notes { get; set; }
[DataType(DataType.Time)]
public DateTime StartTime { get; set; }
[DataType(DataType.Time)]
public DateTime EndTime { get; set; }
public Store Store { get; set; }
}
It also would hurt to add the foreign key reference to the Fluent API.
modelBuilder.Entity<Store>()
.HasMany(c => c.StoreVisits)
.WithOne(e => e.Store)
.HasForeignKey(e => e.StoreId)
.IsRequired();

Entity Framework Navigation Woes

I have Business and BusinessProgram declared as:
public class Business : DbIdEntity
{
public string Name { get; set; }
public virtual Address PhysicalAddress { get; set; }
public virtual Address PostalAddress { get; set; }
public Guid OwnerKey { get; set; }
public virtual Account Owner { get; set; }
public virtual IEnumerable<BusinessProgram> BusinessPrograms { get; set; }
}
public class BusinessProgram : DbEntity<Guid>
{
public Business Business { get; set; }
public ProgramType ProgramType { get; set; }
public DateTime? EffectiveDate { get; set; }
public DateTime? ExpireDate { get; set; }
}
DbIdEntity and DbEntity are just base classes where the primary key (and an autonumbering Id field are declared.
When I query it using this query
foreach (Data.Business business in context.Businesses.Include(b => b.Owner)
.Include(b => b.PhysicalAddress)
.Include(b => b.Owner)
.Include(b => b.BusinessPrograms)
.OrderBy(b => b.Name))
I'm also using a convention that makes properties ending in "Key" the primary and foreign keys instead of the default "Id".
I get the error:
"A specified Include path is not valid. The EntityType
'Data.Business' does not declare a navigation
property with the name 'BusinessPrograms'."
What am I doing wrong?
UPDATE
I used IEnumerable instead of ICollection. Using the correct navigation property type fixed the issue.
I used IEnumerable for my navigation type instead of ICollection. Changing it to ICollection fixed the issue.
I've had rather limited success with using base classes in the way you describe. I'd try "flattening" your model first, and getting it working like that. Then you could try re-introducing the base classes; you might be able to get that working too.
Here it looks as though BusinessProgram should contain a FK property called BusinessProgram_BusinessId if you want to use the default convention. Alternatively, you could give it a different name and use an attribute to override the default convention:
[ForeignKey("Business")]
public int BusinessId { get; set;}

Table Per Hierarchy & Inherited Relationships

I'm using Entity Framework 5, targeting .Net 4.5. For the life of me I can't figure out what I'm doing wrong that's causing the following error while trying to work with Table Per Hierarchy and Navigation columns:
Invalid column name 'Game_Category'.
Invalid column name 'Game_Value'.
Invalid column name 'Type_Category'.
Invalid column name 'Type_Value'.
Here's the abstract base class (note the composite PK on Category and Value):
[Table("Dictionary")]
public abstract class Lookup
{
[Key, Column(Order = 0)]
[StringLength(50)]
public string Category { get; set; }
[StringLength(100)]
public string ExtendedValue { get; set; }
[Required]
public bool IsActive { get; set; }
[Required]
[StringLength(50)]
public string Key { get; set; }
[Key, Column(Order = 1)]
public int Value { get; set; }
}
Followed by two subclasses that add no additional columns...
public class Game : Lookup {}
public class SetType : Lookup {}
Here's the class with Navigation properties to Game and SetType...
public class CardSet
{
[Required]
[StringLength(10)]
public string Abbreviation { get; set; }
public virtual Game Game { get; set; }
[Required]
public int GameId { get; set; }
[Key]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
public DateTime ReleaseDate { get; set; }
public virtual Lookup Type { get; set; }
[Required]
public int TypeId { get; set; }
}
From my data context...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Lookup>()
.Map<Game>(l => l.Requires("LookupType").HasValue("Game"))
.Map<SetType>(l => l.Requires("LookupType").HasValue("Set Type"));
base.OnModelCreating(modelBuilder);
}
The lookup table has a discriminator column named LookupType. I've read through several tutorials on table/inheritance. The other two - TPT and TPC using similarly built objects were a cinch. While I understand the errors above - that it's looking for FK columns by convention, I don't understand what I'm doing wrong or missing that's causing it to look for those columns. I've tried placing ForeignKey attributes over the GameId and TypeId properties, but then I get errors about dependent/principal relationship constraints and I'm not sure how to specify the category as an additional foreign key.
I have yet to find a tutorial on table/inheritance that goes over navigation properties as I'm using them. Any help would be greatly appreciated, this has been driving me nuts for over an hour.
Update:
I believe the problem lies in the use of Category as part of the key. The CardSet doesn't have two properties for the category of "Game" for that lookup or the category for "Set Type" for that lookup. I tried creating these properties but that didn't work. Is it possible to set those using the Fluent API? I've made about a dozen attempts so far without any luck.
I think that EF does not "like" the construct modelBuilder.Entity<Lookup>() to map the two sub classes. This should help:
modelBuilder.Entity<Game>()
.Map(l => l.Requires("LookupType").HasValue("Game"));
modelBuilder.Entity<SetType>()
.Map(l => l.Requires("LookupType").HasValue("Set Type"));

Entity framework Multiple Parent for a child

How can I implement a child that has multiple parents in Entity Framework?
The resulting tables must be as follows:
1.Courses:
CourseID int identity
CourseTitle nvarchar
.
.
.
OtherColumns as neede
2.CoursePreRequisites:
CourseID (FK to Course.CourseID)
PreRequisiteCourseID (FK to Course.CourseID)
or is there any better way to achieve multiple parent for a child record?
You just need two navigation properties in the child class refering to the same parent class and - optionally - two corresponding foreign key properties:
public class Course
{
public int CourseID { get; set; } // PK property
public string CourseTitle { get; set; }
}
public class CoursePreRequisite
{
public int CoursePreRequisiteID { get; set; } // PK property
public int CourseID { get; set; } // FK property 1
public Course Course { get; set; } // Navigation property 1
public int PreRequisiteCourseID { get; set; } // FK property 2
public Course PreRequisiteCourse { get; set; } // Navigation property 2
}
If one or both of the two relationships are optional, use int? instead of int for the foreign key properties.
If you use the property names as indicated in the example above you don't need to configure anything. EF will recognize the two one-to-many relationships by naming conventions.
You can also use collections as inverse properties in the Course entity if you need or want them:
public class Course
{
public int CourseID { get; set; } // PK property
public string CourseTitle { get; set; }
public ICollection<CoursePreRequisite> PreRequisites1 { get; set; }
public ICollection<CoursePreRequisite> PreRequisites2 { get; set; }
}
However, in that case you must specify which navigation property pairs belong together in a relationship. You can do this with data annotations for example:
[InverseProperty("Course")]
public ICollection<CoursePreRequisite> PreRequisites1 { get; set; }
[InverseProperty("PreRequisiteCourse")]
public ICollection<CoursePreRequisite> PreRequisites2 { get; set; }
Or with Fluent API:
modelBuilder.Entity<Course>()
.HasMany(c => c.PreRequisites1)
.WithRequired(p => p.Course) // Or WithOptional
.HasForeignKey(p => p.CourseID);
modelBuilder.Entity<Course>()
.HasMany(c => c.PreRequisites2)
.WithRequired(p => p.PreRequisiteCourse) // Or WithOptional
.HasForeignKey(p => p.PreRequisiteCourseID);

Self referencing / parent-child relationship in Entity Framework

I read quite a number of posts of programmers that run into the Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values -exception when using a self-referencing relationship in Entity Framework.
I am trying to get a parent-child relationship to work:
public class Category {
public int CategoryId { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public Category Parent { get; set; }
public List<Category> Children { get; set; }
}
This is the configuration I use (Fluent API):
Property(c => c.ParentId).IsOptional();
HasMany(c => c.Children).WithOptional(c => c.Parent).HasForeignKey(c => c.ParentId);
//HasOptional(c => c.Parent).WithMany(c => c.Children).HasForeignKey(c => c.ParentId);
Both the HasMany() and HasOptional() configurations result in a "Unable to determine a valid ordering for dependent operations..." exception when I try to save a new category like this:
context.Categories.Add(new Category { Name = "test" });
I don't understand why EF doesn't insert the Category with a null parentId. The database allows the ParentId foreign key to be null.
Would you be able to tell me how to do this?
You must define the ParentId in the category class as nullable to use it as the foreign key property for an optional relationship:
public int? ParentId { get; set; }
An int property cannot take the value null and therefore cannot represent a NULL as value in a database column.
Since someone asked in a comment about doing this with attributes. You can also utilize data annotations to set this up. Using the same example as above:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Category {
// You can also add [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
// as an attribute, if this field is to be generated by the database
[Key] // Define this as the primary key for the table
public int CategoryId { get; set; }
public string Name { get; set; }
[ForeignKey(nameof(Parent))] // Link the Parent object to the ParentId Foreign Key
public int? ParentId { get; set; }
public Category Parent { get; set; }
public List<Category> Children { get; set; }
}
This is tested and works in EF 6.