Dynamic Entity Navigation Property - c#

I have an entity called Asset, similar to below:
public class Asset
{
public int Id { get; set; }
public int TypeId { get; set; }
public int AddedById { get; set; }
public DateTime DateTimeAdded { get; set; }
public virtual AssetType Type { get; set; }
public virtual ITUser AddedBy { get; set; }
}
I want to be able to have a navigation property that is linked to a single table, but that table is dependent on what type of Asset it is. For instance, if the Asset is of the type "Printer" then I want the navigation property to link to the PrinterDetail entity. My initial way of going about this was to have unused columns in the Asset entity, but I figured that was wasteful or bad practice. Is there something that I am overlooking or is this just something that cannot be done?
Thanks for any advice given.

if you want navigate printerDetail by type you can use entityfraemwork inheritance strategy:
Table per Hierarchy (TPH)
Table per Type (TPT)
Table per Concrete class (TPC)
you have to create Model per each type and use TPT strategy for that.
and then you can use fluent api for config mapping for that.
parent Model (Asset) must define as abstract class and AssesTypes Must be Drive from the Parent.
more information

Related

Configure One-None/One Relationship with Multiple Tables using Entity

I'm in a situation where one table has two One-None/One Relationships. How do I implement this using Entity Framework Code-First?
I've seen the following links
https://www.safaribooksonline.com/library/view/programming-entity-framework/9781449317867/ch04s07.html
https://cpratt.co/0-1-to-1-relationships-in-entity-framework/
https://www.tektutorialshub.com/one-to-one-relationship-entity-framework/
Where essentially it's said that the dependent end needs to have a primary key that is the same as that of the principal end. But I'm weary of implementing this with more than one One-None/One Relationship without confirmation and proper knowledge of what's going on. Furthermore I am not sure how to construct statements as it does not have a conventional Foreign Key.
I've also seen Configuring multiple 1 to 0..1 relationships between tables entity framework which confused me beyond recognition.
See below for the relevant part of my DB Diagram:
So Essentially, a Player shouldn't be saved without a DKImage, similarly a Product shouldn't be saved without a DKImage.
Below is the code for Models: Players, Products, DKImages (I know it's not correct, I only implemented it this way so I can generate the database and show the diagram)
Player
public enum Positions { PG, SG, SF, PF, C }
public class Player
{
[Key]
[ForeignKey("Images")]
public int PlayerID { get; set; }
[Required]
public string PlayerName { get; set; }
[Required]
public string PlayerLastName { get; set; }
[Required]
public int PlayerAge { get; set; }
[Required]
public Positions Position { get; set; }
[Required]
public bool Starter { get; set; }
[Required]
[Display(Name = "Active / Not Active")]
public bool Status { get; set; }
//Foreign Keys
public int PlayerStatsID { get; set; }
//Navigation Properties
[ForeignKey("PlayerStatsID")]
public virtual IQueryable<PlayerStats> PlayerStats { get; set; }
public virtual DKImages Images { get; set; }
}
DKImages
public class DKImages
{
[Key]
public int ImageID { get; set; }
[Required]
public string ImageURL { get; set; }
[Required]
public DateTime DateUploaded { get; set; }
//Foreign Keys
[Required]
public int CategoryID { get; set; }
//Navigation Properties
public virtual Products Products { get; set; }
public virtual Category Category { get; set; }
public virtual Player Player { get; set; }
}
Products
public class Products
{
[ForeignKey("Images")]
[Key]
public int ProductID { get; set; }
[Required]
public string ProductName { get; set; }
[Required]
public DateTime DateAdded { get; set; }
//Foreign Keys
[Required]
public int ProductTypeID { get; set; }
//Navigation Properties
[ForeignKey("ProductTypeID")]
public virtual ProductType ProductType { get; set; }
public virtual DKImages Images { get; set; }
}
Edit
I have been told that the code above is correct. If so then how do I create CRUD LINQ Statements (Or any method of constructing CRUD statements for that matter) with the above code.
What you want here is referred to as polymorphic associations: several entities having child entities of one type. They're typically used for comments, remarks, files etc. and usually applied to 1:n associations. In your case there are polymorphic 1:1 associations. Basically these associations look like this (using a bit more generic names):
How to implement them?
Entity Framework 6
In EF6 that's problem. EF6 implements 1:1 associations as shared primary keys: the child's primary key is also a foreign key to its parent's primary key. That would mean that there should be two FKs on Image.ID , one pointing to Person.ID and another one pointing to Product.ID. Technically that's not a problem, semantically it is. Two parent entities now own the same image or, stated differently, an image should always belong to two different parents. In real life, that's nonsense.
The solution could be to reverse the references:
But now there's another problem. The entity that's referred to is named the principal, the other entity is dependent. In the second diagram, Image is the principal, so in order to create a Person, its image must be inserted first and then the person copies its primary key. That's counter-intuitive and most likely also impractical. It's impossible if images are optional.
Nevertheless, since in your case you want images to be required let me show how this association is mapped in EF6.
Let's take this simple model:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Image Image { get; set; }
}
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Image Image { get; set; }
}
public class Image
{
public int ImgID { get; set; } // Named for distinction
public string Url { get; set; }
}
The required mapping is:
modelBuilder.Entity<Image>().HasKey(pd => pd.ImgID);
modelBuilder.Entity<Person>().HasRequired(p => p.Image).WithRequiredDependent();
modelBuilder.Entity<Product>().HasRequired(p => p.Image).WithRequiredDependent();
As you see, Image has two required dependents. Perhaps that's better than two required parents, but it's still weird. Fortunately, in reality it's not a problem, because EF doesn't validate these associations. You can even insert an image without a "required" dependent. I don't know why EF doesn't validate this, but here it comes in handy. The part WithRequiredDependent might as well have been WithOptional, it doesn't make a difference for the generated data model, but at least this mapping conveys your intentions.
An alternative approach could be inheritance. If Person and Product inherit from one base class this base class could be the principal in a 1:1 association with Image. However, I think this is abusing a design pattern. People and products have nothing in common. From a design perspective there's no reason for them to be part of one inheritance tree.
Therefore, in EF6 I think the most feasible solution is to use the third alternative: separate image tables per entity.
Entity Framework Core
In EF-core 1:1 associations can be implemented the EF6 way, but it's also possible to use a separate foreign key field in the dependent entity. Doing so, the polymorphic case looks like this:
The Image class is different:
public class Image
{
public Image()
{ }
public int ImgID { get; set; }
public int? PersonID { get; set; }
public int? ProductID { get; set; }
public string Url { get; set; }
}
And the mapping:
modelBuilder.Entity<Person>().Property(p => p.ID).UseSqlServerIdentityColumn();
modelBuilder.Entity<Person>()
.HasOne(p => p.Image)
.WithOne()
.HasForeignKey<Image>(p => p.PersonID);
modelBuilder.Entity<Product>().Property(p => p.ID).UseSqlServerIdentityColumn();
modelBuilder.Entity<Product>()
.HasOne(p => p.Image)
.WithOne()
.HasForeignKey<Image>(p => p.ProductID);
modelBuilder.Entity<Image>().HasKey(p => p.ImgID);
Watch the nullable foreign keys. They're necessary because an image belongs to either a Person or a Product. That's one drawback of this design. Another is that you need a new foreign key field for each new entity you want to own images. Normally you want to avoid such sparse columns. There's also an advantage as compared to the EF6 implementation: this model allows bidirectional navigation. Image may be extended with Person and Product navigation properties.
EF does a pretty good job translating this into a database design. Each foreign key has a filtered unique index, for example for Person:
CREATE UNIQUE NONCLUSTERED INDEX [IX_Image_PersonID] ON [dbo].[Image]
(
[PersonID] ASC
)
WHERE ([PersonID] IS NOT NULL)
This turns the association into a genuine 1:1 association on the database side. Without the unique index it would be a 1:n association from the database's perspective.
An exemple in your Player table would be this :
public class Player
{
// All the rest you already coded
[Required]
public int ImageID
[ForeignKey("ImageID")]
public virtual DKImage DKImage {get;set;}
}
This would force a player to have a DKImage, but as said in the comments, this create a one to many relationship.
Another way out would be to put all Player fields into the DKImage table, those fields would be null if there is no player associated to this DKImage.
Edit for 1 to 1..0
Ivan Stoev's link got some pretty interesting insight on how to accomplish this :
https://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-3-shared-primary-key-associations
It seems like you will have to put a bit more code in your class :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<DKImage>().HasOptional(t => t.Player).WithRequired();
}
If the tutorial is correct, this would read as :
"DKImage entity has an optional association with one Player object but this association is required for Player entity".
I have not tested it yet.

EF Code First Navigation Property to same table

I'm new to EF and struggling to implement the following scenario. I have an entity I'd like to have a navigation property to another of the same entity. E.g.
public class Stage {
public int ID { get; set; }
public int? NextStageID { get; set; }
public string Name { get; set; }
public virtual Stage NextStage { get; set;}
}
The only example I've found so far was where the entity had a parent / child relationship, i.e. the navigation property was an ICollection of the same entity. I tried adapting this but couldn't get it to work in my instance. Also, I only need it to be one way, i.e. the entity doesn't have a 'PreviousStage' property, just a 'NextStage' one. I'm configuring using Fluent API. Could someone advise if / how this can be achieved?
I am getting this error:
Unable to determine the principal end of an association between the types 'namespace.Stage' and 'namespace.Stage'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations
Edit
Just realised in my slightly simplified example, I didn't show that NextStageID is optional (int?).
You can explicitly define the relation as follows:
public class Stage {
public int ID { get; set; }
public int NextStageID { get; set; }
public string Name { get; set; }
[ForeignKey("NextStageID ")]
public virtual Stage NextStage { get; set;}
}
you need to add a parentId and Parent navigation property
and Children navigation property so entity framework understands that is a recursive relation
check the answer in this stack Overflow link

Entity Framework code first: How to ignore classes

This is similar to questions here and here, but those are old and have no good answers.
Let's say I have the following classes:
class HairCutStyle {
public int ID { get; set; }
public string Name { get; set; }
}
class CustomerHairCutPreference {
public int ID { get; set; }
public Customer Customer { get; set; }
public HairCutStyle HairCutStyle { get; set; }
}
Let's say my HairCutStyle data is stored in a table in another database (I get it from Paul Mitchell himself). I want to use the HairCutStyle class as a POCO class - something that I will use in code to represent hair cut styles, but I don't need to read/write that information in my database. (Assume I have a separate service layer that can populate the data for these classes from the other database.)
How can I tell EF NOT to create a HairCutStyle table in my current db context? But at the same time, I want to store a value in the CustomerHairCutPreference table that is a reference to the HairCutStyle data stored elsewhere. A "virtual" foreign key of sorts, that isn't constrained by an actual database FK constraint.
Add a property in CustomerHairCutPreference for HairCutSytleID and then use the [NotMapped] attribute on the HairCutStyle property. Note, however, that you will then be responsible for ensuring that the HairCutStyle and HairCutStyleID stay in sync.
class CustomerHairCutPreference {
public int ID { get; set; }
public Customer Customer { get; set; }
public int HairCutStyleID {get; set; }
[NotMapped]
public HairCutStyle HairCutStyle { get; set; }
}
Alternatively, you can use the FluentAPI to exclude HairCutStyle completely from ever being mapped by Entity Framework, which may be useful if you have multiple classes that link to it.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Ignore<HairCutStyle>();
}
There are three things to ensure:
Make sure you do not expose a DbSet<HairCutStyle> in your DbContext-derived class
Make sure you do not have any mention of HairCutStyle in your OnModelCreating override
Mark your HairCutStyle property using the NotMapped attribute.

Save a Child for a existent Parent

I have a model with some inherits and it is using nhibernate to persisti on a Database. The nhibernate mapping with fluent nhibernate is working fine, but I have a scenario where I need to save a child for a existent parent. My model looks like this:
public class Item
{
public long Id { get; set; }
public string Name { get; set; }
// other properties
}
public class ItemCommercial : Item
{
public decimal Value { get; set; }
// other properties
}
In my Database, the respective tables are related by Id <-> Id (one per one).
I would like to know, how to Save just a ItemCommercial instance for a existent Item on database. I have the Id of the Item, but I do not know howt to say to nhibernate to say just the Child, instead creating a new Item, for sample:
session.Save(itemCommercialObj); // will create a Item and ItemCommercial with the same Id
Thank you.
As I also answered here
No, it is not possible to "upgrade" an already persisted object to its subclass. Nhibernate simply doesn't support this.
If you safe the subclass with the same ID as the base class, Nhibernate simply creates a copy with a new ID of the object instead of creating the reference to Member...
So basically you could do either
Copy the data of Customer into Member, delete customer and save Member
Use a different object structure without subclasses where Member is a different table with it's own ID and a reference to Customer
Use native sql to insert the row into Member...
you can not the runtimetype of an object like that hence NH does not support it. Change the design to
public class Item
{
public long Id { get; set; }
public string Name { get; set; }
public CommercialValue CommercialValue { get; set; }
// other properties
}
public class CommercialValue
{
public Item Item { get; set; }
public decimal Value { get; set; }
// other properties
}
and a one-to-one mapping. Then it is as simple as setting the CommercialValue property

Using an Interface with a navigation property

I am trying to setup a project using Entity Framework 4, POCO, and Code-Only.
Is it possible in entity framework for type of a navigation property to be an interface?
I have a "Task" class. A Task can be assigned to a user or a group each of which are represented by a separate class and stored in separate tables. The classes look something like this:
public class User : IAssignable
{
public string Name { get; set; }
public int ID { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
public class Group : IAssignable
{
public string Name { get; set; }
public int ID { get; set; }
public string Manager { get; set; }
public string Department { get; set; }
}
public class Task
{
public string Title { get; set; }
public DateTime DueDate { get; set; }
public string Details { get; set; }
public IAssignable AssignedTo { get; set; }
}
Is there a way to may the AssignedTo property as a navigation property in entity framework? I assume there will have to be some type of discriminator for EF to know if it needs to look in the Users table or the Groups table but I can figure out the mapping using Code-Only or EDMX.
you can use interface in navigation property, take a look at this solution as it's the same as question:
How to use interface properties with CodeFirst
I know this is an old question, but no, there is no feature of Entity Framework (even the latest version 6) that allows you to map a navigation property with an interface type.
You could, however, map multiple navigation properties with concrete types (and a constraint that only one may be set) and provide an unmapped property of your interface type which coalesces the concrete navigation properties into a single property. Unfortunately, this may make your queries more complex because certain queries will need to know which concrete navigation properties to reference (and you can't query against your unmapped interface property).
There is significant complexity around support for polymorphic navigation properties. Consider what would have to happen in order to query your original AssignedTo property if you assume it's mapped to a column such as AssignedToId int. You'd have to union or join both User and Group entity sets and hope that a given AssignedToId appears in just one of them. This is the approach used by the Table-Per-Concrete (TPC) type mapping, but it only works with class inheritance (not interfaces) and careful planning for generating distinct ids across the participating types.
You could save yourself a lot of work by using the Text Template Transformation Toolkit (T4) supported by EF4. I found this one after a good 12 hours of looking for a way around manually creating my POCOs and interfaces,
http://blogofrab.blogspot.com/2010/08/maintenance-free-mocking-for-unit.html
Besides providing a brilliant base for unit testing, it auto-generates navigational properties based on the relationships defined in your model.

Categories