NHibernate - Add Comment Property to Entities (Store with Join) - c#

I have a system where I need to be able to add a Comment field onto Customer and Location models but I cannot touch the schema of the existing tables. However, I can add a Comments table. I have simplified this example. We would like the ability to add this Comment to more models moving forward they all use a Guid as Id.
This existing system is a 3rd party system with its own data access layer.
We are just starting to get into NHibernate. From what I can tell it looks like a Join map.
Example:
public class Customer
{
public Guid Id { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string Comment { get; set; }
}
public class Location
{
public Guid Id { get; private set; }
public string Name { get; private set; }
public string Address { get; private set; }
public string Comment { get; set; }
}
Note: we are sure we want the Comment as a 1-to-1 relationship and not a 1-to-many.
How do I configure a separate table just capture Id and Comment? I'm looking for the right terminology to use. I'm looking for examples with XML (and if possible Fluent config). I would like to keep the Comments for all objects in one table. Thanks.

If you can add Comment table (and corresponding key columns in the existing tables) than fluent mapping can look like
public class CustomerMap : ClassMap<Customer>{
public CustomerMap(){
//...other columns mappings
References(c=>c.Comment).Column("CommentId");
}
}
And repeat it for other entities as well. You can set desired fetch-mode(join) and other action there as well. I have wrote References there (so many-to-one) but if you need one-to-one mapping it is not a big difference

If you can't change the database schema your options are very limited.
MAYBE, you can do it using the mapping.
Take a look here:
http://ayende.com/blog/3961/nhibernate-mapping-join
Try to use the same column name in mapping for all entities.

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.

Modeling to use same FK name of a unchanged database

I am using EF6 but...
I can not change the database.
So, if I'm not wrong, I need to create a model that suits the database.
I have to models in relationship one to many:
[Table("ReceCli")]
public class ReceCli
{
[Key]
public int Indice { get; set; }
[Required, StringLength(12)]
[Display(Name = "Nº Documento")]
public string NDOC { get; set; }
[Display(Name = "Banco do boleto")]
[Column("CodBancoBoleto")]
public int CodBancoBoleto { get; set; }
public Banco Banco { get; set; }
}
and
[Table("Bancos")]
public class Banco
{
[Key]
public int CodBanco { get; set; }
[Column("Banco")]
[Required, StringLength(50)]
[Display(Name = "Banco")]
public string Nome { get; set; }
}
In the database this relations are expressing like:
ALTER TABLE [dbo].[ReceCli] WITH NOCHECK ADD CONSTRAINT [ReceCli_CodBancoBoleto] FOREIGN KEY([CodBancoBoleto])
REFERENCES [dbo].[Bancos] ([CodBanco])
GO
ALTER TABLE [dbo].[ReceCli] CHECK CONSTRAINT [ReceCli_CodBancoBoleto]
When executing return an error:
Invalid column name 'Banco_CodBanco'.
I can not change the database.
How can I change the model to EF use ReceCli_CodBancoBoleto name of column instead of Banco_CodBanco ?
You can do model an existing db by hand but you can also tell EF to generate the model from an existing database.
As for your example, a couple of things:
The relationship you have modeled is not one to many but one to one.
Public Banco Banco {get; set;}
Change To:
Public ICollection<Banco> Bancos {get;set;}
There are several ways you can model relationships with EF. Here's a sample of Modeling 1 to many relationships in EF.
The Column attribute is used to match to names in the DB. Make sure your EF CF properties that don't match the database have a Column Attribute. For Your RecCli it should look something like:
[Column("CodBanco")]
public int CodBancoBoleto { get; set; }
or
public int CodBanco { get; set; }
However, you are mapping a 1 to many relationship so having the CodBancoBoleto is not needed. Just use the navigation property of Public ICollection<Banco> Bancos {get;set;}. This should suffice except you might have to put a ForeignKey attribute for it telling it to use CodBanco as the key for the navigation.
[ForeignKey("CodBanco")]
Public ICollection<Banco> Bancos {get;set;}
You might have to do this for all your keys as the default code first convention for keys end with Id. I say might as your Banco Class's key is named properly CodBanco and marked with the Key. So you might be fine.
A final note is that you appear to be trying to use the constraints name for the mapping. You don't use the constraint name, rather the actual column names, aka the references part of the constraint.

Dynamic Entity Navigation Property

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

How to ask Automapper to grab related record by inner join on Id field which is not a foreign key?

I’ve been using Automapper for a while now, and so far it all works great. But recently I came across some “limitation” (or lack of my knowledge).
Let me give you a simplified example with two classes:
public class Consumable
{
public int ConsumableId { get; set; }
public string Description { get; set; }
public int SaleDepartmentId { get; set; }
}
public class SaleDepartment
{
public int SaleDepartmentId { get; set; }
public string Description { get; set; }
}
These two entities store the Id of SaleDepartment, but there is not foreign key linking SaleDepartment to Consumable (and I don’t want it as a key), however SaleDepartment has PrimaryKey on SaleDepartmentId
Now my DTO looks very similar
public class ConsumableDTO
{
public int ConsumableId { get; set; }
public string Description { get; set; }
public int SaleDepartmentId { get; set; }
}
Here is the mapping
Mapper.CreateMap<Consumable, ConsumableDTO>().ReverseMap();
So anytime I bring a Collection of ConsumableDTO’s I also want to bring the related SaleDepartment’s descriptions,
If there was a navigation property I would do something like this
Mapper.Map<ObservableCollection<Consumable>>
(context.Consumable.Project().To<ConsumableDTO>());
But because such a key does not exist, how would I tell the automapper to do inner join based on these Ids I have?
I have spent two days and I found a way of doing it, but I am not convinced that this the right way, and I am wondering whether I am missing a trick here and there is an easier or better way of achieving this with the automapper.
This is how I achieved getting the related record
var foo = new ObservableCollection<Consumable>(
(from c in context.Consumable.Project().To<ConsumableDTO>()
join sd in context.SaleDepartment on c.SaleDepartmentId equals sd.SaleDepartmentId
select new
{
consumable = c,
SaleDepartmentDescription = sd.Description
}).ToList()
.Select(p => Mapper.Map<ConsumableDTO, Consumable>(p.consumable, new Consumable()
{
SaleDepartmentDescription = p.SaleDepartmentDescription
})));
So, this will grab or consumable and then inner join saledeparments and select description form that inner join, but it seems like quite few steps, is there an easier way of telling the automapper, grab that related record based on this matching Id?
Thank you for your attention and time.
First, I'm assuming your DTO is meant to contain public string SaleDepartmentDescription { get; set; } as your question refers to it but it isn't actually there.
If you are NOT using EF migrations (a fair assumption since otherwise you'd just add the foreign key!), then you can do this by adding keys in your Entities - the keys don't actually need to present in the database for EF to join on them, this just tells EF to pretend that they are. (If you are using EF migrations then this approach will not work, as it will want to add the keys to the DB.)
public class Consumable
{
public int ConsumableId { get; set; }
public string Description { get; set; }
public int SaleDepartmentId { get; set; }
[ForeignKey("SaleDepartmentId")]
public virtual SaleDepartment SaleDepartment { get; set; }
}
Assuming your DTO does contain the string property SaleDepartmentDescription then AutoMapper will handle this automatically, though you should use ProjectTo to make more efficient database queries:
var mappedDTOs = context.Consumable.ProjectTo<ConsumableDTO>().ToList();

Class linking best practices in C#

First off, EF is not an option for our development environment so please no "just use EF" answers ...
I think this is a pretty standard dilemma so I'm sure there must be a way that most Pros do it that I just have not stumbled across ... so I'm out here hoping y'all can show me what it is.
Let's say you have the following database tables:
tblCompanies
ID
NAME
tblDepartments
ID
COMPANY_ID
NAME
tblEmployees
ID
DEPARTMENT_ID
FIRSTNAME
LASTNAME
... what's the best way to represent this in Classes within your code?
I assume the best way is like this:
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public List<Department> Departments { get; set; }
}
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set;}
public string LastName { get; set; }
}
I believe that to the be the "OOP Proper approach" to this. However, what seems to always happens is something like this:
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public int CompanyID { get; set; }
public List<Employee> Employees { get; set; }
}
... mainly because when you pull just a Department from the database you are only going to have Company ID, not all the other attributes needed to fully populated an instance of the Company class.
(I've used a pretty vanilla example here but the one I'm actually tackling in my current project has 3 fields that it uses to link the data together so the thought of having the same 3 fields in several classes seems wrong to me)
Is there a Best Practice for these scenarios? As much as I don't like the thought of storing the same data in multiple classes just out of laziness, I also don't like returning an instance of a class with just one of its fields populated because that's all I had at the time.
This is a common problem, and one that ORMs try to solve. To be sure it isn't an easy one depending on what your wants are and what your constraints are.
There are only two fundamental options to keep one copy of the information. Lazily load the data as requested or load it all to begin with (Greedy load). Otherwise you have to duplicate the data.
With lazy loading you basically set things up such that when navigating into a property you make a call to the database and grab the information needed to load the entity representing the property you are accessing. The tricky part to watch with this is the SELECT N + 1 problem. You experience this problem when you end up iterating a set of parent entities and trigger lazy loads on every child entity, thus resulting in N+1 calls to the database to load a set of entities (1) and their children (N).
Greedy loading basically says load everything you need to start with. ORMs (where they work) are nice because they take care of many of the details via LINQ and create solutions that can be performant and maintainable usually along with the ability of allowing you to manipulate the usage of Greedy and Lazy Loading.
Another important gotcha is many to many relationships. You need to make sure not to have circular initialization, and get all the baggage of circular dependencies. There are surely many more I have missed.
In my humble opinion I am not so sure there is a best practice as much as there are practices with some of them bad - nothing is perfect. You can:
Start rolling your own object relational mapper allowing you to get rid of the duplicate ID
Use a lighter ORM framework to handle some of this allowing you to get rid of the duplicate ID
Create specialized queries to load aggregations of data allowing you to get rid of the duplicate ID (* cough * DDD)
Just keep the duplication of the ID like you mention above and not worry about creating an explicit relational model in your domain.
This one is on you to choose what is best based on your constraints. This is a deep topic and my experience is limited...so take what I am saying with alot of salt.
I don't think there's a "best practices" manual for this kind of things, and surely it depends on how your classes are going to be used. But in my personal experience, I have ended up following this approach:
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public IEnumerable<Department> GetDepartments()
{
// Get departments here
}
}
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
protected int CompanyID { get; set; }
private Company _Company;
public Company Company
{
get
{
// Get company here
}
}
public IEnumberable<Employee> GetEmployees()
{
// Get employees here
}
}
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
protected int DepartmentID { get; set; }
private Department _Department;
public Department Department
{
get
{
// Get department here
}
}
public IEnumberable<Employee> GetEmployees()
{
// Get employees here
}
}
In some cases I have exposed some of the "navigation" properties of my classes as public (like CompanyID and DepartmentID) to prevent the instantiation of a new class to get a value that has been loaded already.
As others have noted, you could also simulate "lazy loading", but this will require some extra effort from your part.
I would think it depends on requirements. Do you need to traverse upward (get company from department, department from employee, etc). If you do, then it is best that you provide a means of doing that. Ideally that would be something like a Company or Department property, of course you wouldn't want to get data you don't really need, so you'd likely keep a private company id and have a public getCompany function which queries for the data.
I believe that this is not a really OOP question, in your case you just have an database model (database representation in classes) which does not contain any logic and all the classes are used as structs, and this is a right way to map your database to classes - structs. So in your next module which will represent the logic of your program you have to map your database module to the real classes which will contain the logic (I mean methods which will implement it) of course if you really need them. So in my opinion the OO question should be in the logic part of your application. On the other hand you could take a look on nhibernate and how the mapping done in there it will give you a hint for the bes database model implementation.
I believe this is what your classes would look like in NHibernate:
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public IList<Department> Departments { get; set; }
}
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public Company Company { get; set; }
public IList<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set;}
public string LastName { get; set; }
public Department Department { get; set; }
}
Note that there is a way to navigate from Employee to Department and from Department to Company (in addition to what you already specified).
NHibernate has all kinds of features to make that just work. And it works very, very well. The main trick is run-time proxy objects to allow for lazy loading. Also, NHibernate supports a lot of different ways to eager and lazy load just exactly how you want to do it.
Sure, you can get these same features without NHibernate or a similar ORM, but why wouldn't use just use a feature rich mainstream techology instead of hand coding your own feature poor custom ORM?
There is another option. Create a 'DataController' class which handles the loading and 'memoization' of your objects. The dataController maintains a dictionary of [CompanyIDs, Company objects] and [DepartmentIDs, Department objects]. When you load a new Department or Company, you keep a record in this DataController dictionary. Then when you instantiate a new Department or Employee you can either directly set the references to the parent objects OR you can use a Lazy[Company/Department] object and set it using a lambda (in the constructor) which will maintain the scope of the DataController without it being referenced directly inside the objects. One thing I forgot to mention, you can also place logic in the getter / get method for the Dictionaries that queries the database if a particular ID is not found. Using all of this together allows your Classes (Models) to be very clean while still being fairly flexible as to when / how their data is loaded.

Categories