Entity Framework Core Code First Model Navidation Properties - asp.net-core

I have a Web API that uses entity framework. I have several tables there were created using the code first setup. My Competitions class is defined below.
Everything works great and I'm able to get my Competitions table data along with all the data in the navigation properties that are returning a collection. However, I'm not able to get any values for the CompetitionTypes and Users navigation properties. OwnerId references UserId in the Users table.
How would I get the linked data in my CompetitionTypes and Users table? I basically want the same thing as the three collection navigation properties, except that CompetitionTypes and Users would only return one row.
public partial class Competitions
{
[Key, Required]
public int CompetitionId { get; set; }
public int CompetitionTypeId { get; set; }
public int OwnerId { get; set; }
public string CompetitionName { get; set; }
public CompetitionTypes CompetitionTypeId { get; set; }
public Users UserId { get; set; }
public ICollection<Participants> Participants { get; set; }
public ICollection<ResultStats> ResultStats { get; set; }
public ICollection<Results> Results { get; set; }
}
}

EF auto-matches FK properties with navigation properties based on conventions. Namely, it expects FK properties to be named the same as navigation properties, just with Id at the end. In other words, for it to automatically match up OwnerId, you'd need a navigation property like:
public User Owner { get; set; }
Since your navigation property is UserId, it's actually looking for a property named UserIdId.
If you don't want to follow conventions, then you must either use the ForeignKey attribute or fluent config to tell EF which property belongs with which.
That said, there's some pretty major issues with your naming of things here. First, entities should always be singular User, not Users. Second, you should not have navigation properties that end with Id: e.g., User, not UserId. Only actual PK or FK properties should end with with Id. Finally, don't prefix properties on your entity with the entity name. This last one is mostly for readability. Which is more natural: competition.Id or competition.CompetitionId? Likewise with CompetitionName; it should just be Name. And, for what it's worth, you don't need Required for either a primary key or a non-nullable type (such as int). In either case, the property is required by default.

Related

Confused about DTOs when reading and editing. How to desing DTO for filling the form in VUEjs app?

I am trying to develop an enterprise-level application. I have domain and application services. I have created my DTOs for multiple purposes separately. But confused about which way I should use them from the API viewpoint.
I have complex objects lets say,
public class Entity{
public int Id { get; set; }
public string Name { get; set; }
public int? ManufacturerId { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
}
public class Manufacturer{
public int Id { get; set; }
public string Text { get; set; }
}
And I have corresponding DTOs designed with composition now. It was separated before.
public class EntityBaseDto{
public string Name { get; set; }
}
public class EntityReadDto : EntityBaseDto{
public string Manufacturer { get; set; }
}
public class EntityWriteDto : EntityBaseDto{
public int? ManufacturerId { get; set; }
}
Now the question is,
I have a table which is filled with List<EntityReadDto> which is clear. Before, EntityReadDto also had the ManufacturerDto as fully included with id and text. Whenever I require to edit one of the entries from the table I was able to load the dropdown selected items or list of tags etc with the ids attached to the Manufacturer objects within ReadDtos. Now it is not possible. Since I wanted to simplify the codes I just converted them to strings that are read-only. Now I have created another endpoint to get an editable version of the record when needed. Ex: EntityWriteDto will be used to fill the form when the edit is clicked on a specific item. The manipulation will be carried on that DTO and sent with the PUT type request to edit the record.
I am not sure if this approach is ok for these cases. What is the best practice for this? I have many objects related to the entities from other tables. Is it ok to make a call to get an editable version from the backend or need to have it right away in a VUEjs app?

One-to-one entity framework

I am doing the entity framework code first to set up my database.
I have two classes where their relationships are one-to-one, Lecturer & LoginInfo.
public class Lecturer
{
public int LecturerId { get; set; }
public string FullName { get; set; }
public int UserId { get; set; }
public LoginInfo LoginInfo { get; set; }
}
public class LoginInfo
{
public int UserId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool ChangePassword { get; set; }
public Lecturer Lecturer { get; set; }
}
So for my entity framework, I have written this for the one-to-one relationship.
modelBuilder.Entity<Lecturer>()
.HasOne(input => input.LoginInfo)
.WithOne(input => input.Lecturer)
.HasForeignKey<Lecturer>(input => input.UserId);
From the code above, does it mean that Lecture has one LoginInfo, LoginInfo with one Lecturer and Lecturer has a UserId as a foreign key?
Another question would be, for this one to one relationship, do I have to write another set of code for LoginInfo like this:
modelBuilder.Entity<LoginInfo>()
.HasOne(input => input.Lecturer)
.WithOne(input => input.LoginInfo)
.HasForeignKey<LoginInfo>(input => input.LecturerId);
I am just a beginner trying to learn, thanks for helping :).
From the code above, does it mean that Lecture has one LoginInfo, LoginInfo with one Lecturer and Lecturer has a UserId as a foreign key?
Correct. It also means that LoginInfo is the principal and Lecturer is the dependent end of the relationship. Also since the FK property is not nullable, the relationship is required, i.e. in order to create Lecturer you have to create LoginInfo first, which is not associated with another Lecturer.
Also note that since the UserId is not following the default convention for PK name, you should explicitly configure it as PK of the LoginInfo:
modelBuilder.Entity<LoginInfo>()
.HasKey(e => e.UserId);
Another question would be, for this one to one relationship, do I have to write another set of code for LoginInfo like this
No. Single relationship requires single configuration and single FK. If you do so, you would be defining a second relationship, which also would create circular dependency between the entity, which should be avoided in general. The first fluent configuration fully defines the desired relationship and is enough to handle loading related data and other CRUD operations.
For more info about terms, relationship types and configuration, see Relationships section of the EF Core documentation.

Fluent NHibernate one-to-many with intervening join table?

I'm having trouble getting the Fluent Nhibernate Automapper to create what I want. I have two entities, with a one-to-many relationship between them.
class Person
{
public string name;
IList<departments> worksIn;
}
class Department
{
public string name;
}
The above is obviously bare bones, but I would be expecting to generate the fleshed out schema of:
Person{id, name}
Department{id, name}
PersonDepartment{id(FK person), id(Fk Department)}
Unfortunately, I am instead getting:
Person{id, name}
Department{id, name, personid(FK)}
I don't want the FK for Person included on the department table, I want a separate join/lookup table (PersonDepartment above) which contains the primarykeys of both tables as a composite PK and also Fks.
I'm not sure if I am drawing up my initial classes wrong (perhaps should just be LIst workIn - representing ids, rather than List worksIn), or if I need to manually map this?
Can this be done?
The way the classes have been structured suggests a one-to-many relationship (and indeed that's how you describe it in your question), so it should not be a surprise that FNH opts to model the database relationship in that way.
It would be possible, as you suggest, to manually create a many-to-many table mapping. But, is this definitely what you want?
I tend to find that pure many-to-many relationships are quite rare, and there is usually a good case for introducing an intermediate entity and using two one-to-many relationships. This leaves open the possibility of adding extra information to the link (e.g. a person's "primary" department, or perhaps details of their office within each of their departments).
Some example "bare-bones" classes illustrating this kind of structure:
public class Person
{
public int Id { get; set;}
public string Name { get; set;}
public IList<PersonDepartment> Departments { get; set; }
}
public class PersonDepartment
{
public int Id { get; set; }
public Person Person { get; set; }
public Department Department { get; set; }
public bool IsPrimary { get; set; }
public string Office { get; set; }
}
public class Department
{
public int Id { get; set; }
public IList<PersonDepartment> Personnel { get; set; }
public string Name { get; set; }
}

How to use look up values with NHibernate?

How do you handle look up values with NHibernate? For example, I have an Order entity and it has a BillingAddress property that is a value object named Address, it's simple if the Address object just contains State and Country properties as strings. But what if I want a Country contains a list of its states the Order form can populate appropriate state dropdown list for each selected country.
Can I still create Country and State as value objects? Or they must be entities? And if they are entities, can Address be a value object?
Below is a sample code of my example:
public class Order
{
public virtual int OrderId { get; set; }
public virtual Address BillingAddress { get; set; }
}
public class Address
{
public virtual State State { get; set; }
public virtual Country Country { get; set; }
}
public class Country
{
public virtual string Name { get; set; }
public virtual ICollection<State> States { get; set; }
}
public class State
{
public virtual string Name { get; set; }
public virtual Country Country { get; set; }
}
If you want to store the lookup data in the database, then they need to be entities. Otherwise, it is up to you. If you do, I suggest marking them as immutable and putting them in a read only 2nd-layer cache.
If you store them as values, and they have multiple fields like Abbrevation, Name, Coordinates, etc. then you can save the id as a value in the data store, and have the lookup data hard-coded as a plain C# class. You'll just retrieve the id value from NHibernate, and then your calling code will have to run the lookup methods on the class. Not as elegant, but simplifies from the NHibernate/database perspective.
Either method is acceptable--it more depends on how you plan on using them: who is maintaining and using the code at each level, where you want the caching and/or lookup code, if you control the calling code or not, etc.

Fluent NHibernate - Map 2 Identical classes to same table

I've seen this (unanswered) question asked once before, but in a different context. I'm looking to have two domain objects map to the same table, WITHOUT a discriminator. The two classes are:
public class Category
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual ReadOnlyCategory ParentCategory { get; private set; }
}
and
public class ReadOnlyCategory
{
public virtual int Id { get; private set; }
public virtual string Name { get; private set; }
public virtual ReadOnlyCategory ParentCategory { get; private set; }
}
The main difference is that all public properties of ReadOnlyCategory are read-only. My idea here is that I want all users of this class to know that they should only mess with the category they are currently 'looking' at, and not any other categories in the hierarchy. (I've left off other properties regarding the subcategories.)
Clearly, in the database, Category and ReadOnlyCategory are the same thing, and NHibernate should treat them very similarly when persisting them. There are three problems wrapped into one here:
1) How do I do the mapping?
2) When instantiating the objects, how do I control whether I instantiate Category or ReadOnlyCategory?
3) When persisting the objects, will the mapping be smart enough, or do I need to use an extensibility point here?
Any pointers on how I can get this to happen?
(Or am I crazy?)
This looks like wrong object model design to me. I don't see a good reason to introduce a new class just for authorisation reasons (whether user allowed to modify a given category object?). You may as well use one class and throw for example InvalidOperationException if an end user is not supposed to modify a category.