Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
With the risk of being labeled off-topic I am going to ask it any way :-)
I recently joined a new development team and they do have a habit of doing the following. While I have always considered it an anti pattern I just find out that I can't explain why. So, I am just curious to get your opinions.
Let consider the following situation: You have an invoice application, when a new invoice needs to be created, it has to get a new unique invoice number (like INV0001). Of course, it will be stored in the DB, in a table having an auto increment field 'id'. So, just generate the Number from the id.
class Invoice{
[Key]
int Id { get; set;}
string Number => String.Concat("INV", this.Id.ToString().PadLeft(4, '0'));
}
I have always (blindly) obeyed the rule "don't use an id as a business value". but I can't really motivate it.
don't use an id as a business value
You can apply same explanation which used for motivating of Separation of concerns.
If in business logic code you are using features of implementation details of Id, for example generated by database, this mean that your business logic depend on database implementation.
Id have one responsibility - provide unique value, by which you can identify entity and link it with other related entities. So in your business logic you can use Id value only for equality conditions.
For example if you have Id of type integer generated by database.
And you have somewhere in the business logic condition
if (Id == 0)
{
return "new";
}
Your business logic will depend on Id implementation (type). Which mean you can use only Id of value integer and can not change it to Guid for example.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am creating a web app using ef core, and I have three entites, Student, Teacher, and Project. Now each of these tables needs to have multiple Links (Id & Url columns here) that point somewhere on the web. What is the best way to design this relation.
I've thought adding a StudentId, TeacherId, and ProjectId nullable column to the Links table. I've thought of creating a Links table for each entity. I've also thought of using a discriminator column, but still, it doesn't feel right.
How do I properly design this?
Note: The Student and Teacher table have a one to one relation with a user table, so I could just put the foreign key there, but the Project table is unrelated to these.
Based on the comments the link, you have a set of links for some or each of your entities in question.
But these are attributes, even a link array is an attribute of those entities, as a link is not an entity on its own. Unfortunately, 1NF requires each attribute to have a unique value. But let's be serious: is this an unbreakable constraint? Of course not. Some RDBMS do have array columns. SQL Server does not. But it has XML and JSON column types. EF has some other tools to provide the same.
Actually it depends on what do you want to do with those links: are they somehow processed with SQL or not. If only the upper tiers are handling them - and I suppose they are processed on the visualization tier - from the database point of view the link array is a single attribute.
If those links are passing trough your business logic, and they are only used during rendering, you can simply store them as comma-separated lists, or JSONS text in a nvarchar with a string property counterpart in the EF entity class, and split/parse them only on the visualization tier. That would make the less concentrated effort.
If your business logic needs them separately, EF does have support for complex types. You can still store your arrays as JSON text in a nvarchar column and serialize-deserialize them transparently. Check here: https://www.codeproject.com/Articles/1166099/Entity-Framework-Storing-complex-properties-as-JSO even better solution here: https://entityframework.net/knowledge-base/14779740/can-i-embed-an-object-in-an-ef-entity--serialize-on-save--deserialize-on-access--
SPARSE is still there of course, if applicable.
You can use below three mapping tables. Which are maintain your many to many relationship.
Like: 4 to 5 students working on same link.
2 teachers handling same link.
create table student_link_mapping(slmid int identity(1,1), studentid int not null, linkid int not null)
create table teacher_link_mapping(tlmid int identity(1,1), teacherid int not null, linkid int not null)
create table project_link_mapping(plmid int identity(1,1), projectid int not null, linkid int not null)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm working on a project with angular + net core 2.1 and entity framework core.
In my back end I have this structure:
FooController -> FooService -> FooRepository -> FooEFContext
Controllers only route requests to the right service(s).
Services know the business logic of how things work.
Repositories abstract EF.
EFContexts access data.
Now, imagine I have a two entities of this kind:
Employee n...1 Company (where a company may have n employees and an emply only 1 company)
And now imagine I'm at the point when I want to update the company data of a specific employee:
public void Post([FromBody]Company newData) {
var user = _userService.GetUser( // id of current logged user );
...
// Get the company associated with the user
...
_companyService.Update(company)
}
How should I get the company? I have two alternatives in my mind:
_userService.GetUser(..) returns the user with all the details of the associated entities (company, location, .. others)
_userService.GetUser(..) returns just the user info, without including all the details, then I call:
_companyService.GetCompany( user.companyId)
In the first case I may have to have 2 different methods in my service: one that gets only the user data and another that gets the user data plus all the details of all the associated entities.
In the second case I do two roundtrips to the database, but I keep a more strict "single responsibility" concept for each service.
Which do you think is the better approach? Is there something I'm missing?
Thank you so much :)
I have questioned myself on this scenario a bunch of times as well, but I really think that keeping things small with single responsibility is the way to go (so your second option). You state that the downside is more DB calls (which is good to be aware of), but in this instance I think that additional call doesn't warrant returning all associated entities together.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Let's suppose we have 2 tables:
Person
ID
Name
Nationality_ID (FK)
Nationality
ID
Name
With EF, in what contexts does it make sense and is correct to use each of the options below to add a nationality to a person? What is the different between them? What is the faster and the slower?
Option 1:
TheNationality.persons.Add(ThePerson);
Option 2:
ThePerson.nationality_id = TheNationality.id;
Option 3:
ThePerson.nationality = TheNationality;
If Person is the root of your aggregate and the focus of your application, most likely option 2 and option 3 make sense. Of those, option 3 is the more useful if you need to do additional domain logic based upon information in your nationality. Option 1 makes sense if the focus of your application is about nationality.
None of these methods is mutually exclusive. If you query and manipulate the objects from both perspectives, you can use options 1/3 or 1/2.
The resulting insert/update would be the same in all cases. Unless it is necessary to get TheNationality entity for some other reason, you could skip the read to obtain that and just assign the ID if you have it:
ThePerson.nationality_id = someNationalityIDVariable;
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is there any preference on either appending DTO or Entity to a class name?
Is there any standard around this?
1 Class is used by ORM (EntityFramework) and the other class is used for serialization.
The reason for this is so that there is no duplication of all fields as the EntityFramework is a wrapper around the DTO class(most but not all properties).
The DTO class is in a shared library, and decoupled from EF.
E.g. Which of these is the most common/standard approach?
// 1.
MyNamespace.Entities.MyClass
MyNamespace.Models .MyClassDto
// 2.
MyNamespace.Entities.MyClassEntity
MyNamespace.Models .MyClass
// 3.
MyNamespace.Entities.MyClassEntity
MyNamespace.Models .MyClassDto
In my personal experience your third example is the only implementation I have worked with and it is the one I would argue for because the intent of the object you are working with will always be clear whereas with the other two it only becomes clear when looking at both objects together.
That being said as long as your team comes to an agreement on which to use any would work.
In my opinion, you typically don't want to put implementation details into class names for similar reasons to why you don't want to use Hungarian Notation.
If there's a bit of code that needs to work with both types and differentiate between them, another option is including aliased using statements like this:
using entities = MyNamespace.Entities;
using dto = MyNamespace.Models;
//in code
var myClassEntity = new entities.MyClass();
var myClassDto = new dto.MyClass();
//work with both
My assumption is that the code that needs to work with both types is limited to an isolated library, and that client code typically works with one, not both types.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I would like to build some sort of survey/ auditing software.
I am brainstorming how to build my classes and if there is a design pattern that could support me. Because ther must be something that makes life eaysier...
My application should have questions which contains a title and a description.
And then I have multiple types of answers.
So... one type could be a yes/no answer
Another type could be a value between 1 and 10.
Another type could free text answer
Another type could be a three given text choices where you can select one (The dinner was excellent, good, nod bad)
So on the survey planning site I would write down my questions and assign answer types.
And on executing the survey I want to tread it like a collection of questions with an answer...
Basically the question is how to unify all the different answer types and how to store them in the database?
I looked at composite and strategy pattern but I am not sure...
and I know there is not perfect solution and it always depends...
But it would be great if someone can share best practice on how they dealed with similar topics...
Thanks in advance...
What you seem to be asking here is what are the different entity mapping strategies that are available to you in the database? In short you can have:
a table per entity
a single table for all entities with a discriminator value to identify each one (values could be just a tokenized string for example) - essentially a big Map
a table per entity with 1:1 join for optional properties
Your ORM solution then reads the data back from the database and turns it into the appropriate type of object (the entity) populating the fields as it goes.
In terms of the middle tier, you will need the following classes:
AbstractQuestion
An abstract base class for questions. Containing title, description and abstract ask() and answer() methods. There will be a variety of subclasses for AbstractQuestion that provide different display messages depending on the type of question. For example, MultiChoiceQuestion will implement the ask() method in such a way that the title and description get displayed (you could pull this up into the AbstractQuestion ask() method) along with all the choices available (which is specific to each subclass). This could be generalised so that ask() takes a Map as a parameter which can be populated with anything you like. Or you could use varargs - whatever.
Answer
Just a simple class containing a Map with known keys representing the different aspects of the answer with a reference to the owning AbstractQuestion.
Questionaire
A collection of AbstractQuestions arranged in a list. For each AbstractQuestion call the ask() method, wait for user input, then call the answer() method with the provided data.
No need for complex design patterns, unless you count abstract base classes as a pattern. The above is not complete, but it should be enough to get you started.