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 days ago.
Improve this question
Context:
I am writing a web application using SQL server database, C# MVC API layer, Next (React) front end. The database is already created and populated and is in full Third Normal Form (3NF) and the base entity classes have been autogenerated from the database, so using a database-first modelling approach. This will seem like a bit of a rant, but I want to know if I am approacing this correctly because it feels like an awful lot of boiler plate code but this may just be because my project is not big enough to reap the benefits.
These aren't my tables but the relationship is the same; namely 1:many relationships with a primary key of ParentTable.id and foreign key of ChildTable.ParentTable_id
Consider a system with 4 tables: Store, Customer, Order, OrderLine. Each customer belongs to only one store and each order belongs to only 1 customer. The base models have their respective links (1 Parent => N Children) and Inverse Link (1 Child => 1 Parent). When you call the .../api/store it doesn't contain any customers by default. If you modify the controller
_context.Stores.Include("Customers").ToListAsync()
This throws an error when returning it as JSON because of the cyclic link so I need to create ViewModels for both the Customer (exluding the Stores model, but just keeping the storeID) and for the Store (including the collection of CustomerViewModel). This is fine while this is the only VM I need for customer or store but what if I also need a customer view model that includes the orders, or a viewmodel for the marketing team and a different one for the finance team. What options do I have? I am thinking either different model names within the same namespace
StoreCustomerViewModel
FinanceCustomerViewModel
MarketingCustomerViewModel
or using namespaces
using ...models.finance -> CustomerViewModel
using ...models.marketing -> CustomerViewModel
Or am I thinking about this the wrong way? If I need to combine models (e.g. where the main model contains a collection of other models - Customer.orders = List-OrdersViewModel) can these cut across namespaces and if so how and what are the caveats around that.
I'm not sure but once I stumbled upon a similar problem (Eager Loading).
Some advised to use [JsonIgnore] above the properties I don't want.
others advised to add UseLazyLoading() in my program.cs
But what really worked for me was creating DTOs and using AutoMapper.
So try out each option and see what works for your project.
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 have different product types that have different attributes. They cannot be stored in a single table as the attributes are too distinct. There's a couple of options I'm currently looking at: EAV and a table for each type.
My situation is, at the moment, there are only a number of types (lets say 8) but in the near future with almost 100% certainty, this can grow. But the growth is controlled by me, its not defined by users. It will be up to me to grow the product type.
I'm currently inclined to use EAV (for the reason that I can cover the growth easily - I think) but I am not sure as I'm concerned with the performance as well as modeling them in my language of choice (C#). My question is, given the scenario above, is it better for me to create a single table for each product type and add as necessary, or would this be a good case (or not even good, lets say acceptable) to use EAV?
There's no short good or bad answer to this concern, because it depends of many things.
Do you have a lot of product types ?
How do you think each of them will evolve (think to what will happen when you will add new fields to products) ?
Do you need to handle "variants" of the products ?
Do you intend to add entirely new types of products ?
Etc.
EAV is probably a good way to go if you answer if you answer "yes" to some or all these questions.
Regarding C#, I have implemented in the past an EAV data catalog with it, and using Entity Framework over SQL Server (so a RDBMS).
It worked nice to me.
But if you need to handle a lot of products, performance can quickly become an issue. You could also look for a "NoSQL" solution, did you think about it ?
Just keep in mind that your model object does not have to match your data model.
For example you could perfectly have a stronly typed object for each type of product if you need so.
Much depends on the operations that will be performed on entities. If you will:
often add new attributes to products;
add a lot of products type;
implement full product type search (or other "full product type" feature);
I recommend you to use EAV.
I have implemented in the past EAV data structure with ADO.NET and MS SQL and don't have any problem with performance.
Also, Morten Bork above recommend use "sub types". But if you want implement some "full product type" features, I think it will be more difficult then use pure EAV model.
EAV doesn't really play well with a relational database. So if that is what you are doing. (IE connecting to SQL) Then I would say no. Take the hit in development time, and design a table pr type of product, or make a aggregate table that holds various properties for a product type, and then connect the properties to the relevant tables.
So if a product contains "Cogs" then you have a table with "teethcount", "radius" etc.
Another product type has "Scews" with properties "Length", "riling" etc.
And if a product type has both cogs and screws, it merely has relation to each of these subtypes.
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 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 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 9 years ago.
Improve this question
I am designing a C# ASP.Net web application that uses a lot of common functionality and the right way to deal with that seems to be through inheritence. I plan to make a base class (Person) and the inherit it in other classes like Employee and Vendor, and then in turn inherit Employee with Manager, etc. That way I don't have to define common properties such as FirstName, LastName, PhoneNumber, etc. on each one of them.
The second part of the questions is this: If I use inheritence and use Entity Framework's CodeFirst entities, will they understand the inheritence? How will the data be stored in the tables? Will each table have a FirstName and LastName column, or is EF smart enough to make them a common table?
I am really hoping someone who is a REAL object oriented programmer out there can help me clear this up. I have gotten a lot of conficting information and I need someone with actual experience on EF projects to give me some guidance. Am I understanding inheritence right? If not, what am I getting wrong? Any help is appreciated.
Thanks,
Bert
This is not an easy question, but for most cases it's better to choose composition instead of inheritance. You should not derive cash dispenser from calculator just because calculator has display and keyboard properties. It's ridiculous.
But sometimes inheritance makes sense. Ask yourself, should those classes have 'is a' relationship? As I see your task, it's better to make Vendor and Employee to be independent classes, both have Person property. And derive Manager from Employee.
Nevertheless keep depth of inheritance as little as possible. Deep hierarchies are pain to debug and understand, especially if there are many method overrides.
For more inspiration about the topic have a look at Chad Myers blogpost.
From an object-oriented perspective, the problem with that approach is when a person becomes a manager, a employee, a vendor or all of them. In some latin languages we have to forms for the verb to be (ser/estar). The former refers to the nature of the being and later to the state. It is better to use isA for inheritances when refers to the nature of the being rather than its state. In your case, I would recommend using roles. A person has many roles. Manager is Role (Manager inherits from Role), Employee is Role, etc. This way, you can reuse your person attributes and you can add and remove roles of a person.
First 1: Sounds good. But make sure that an "is a"-relation is given. Do not derive Person from Address just to include the Address-specific properties - use EF complex types for this kind of reuse.
One issue that comes to my mind: Are you sure that Vendor is a sub type of Person?
More on that: make sure that you stay within "one domain" with your inheritance. As Vinny posted in another possible answer, if the same Person could be Manager AND CustomerContact and both inherit from Person you run into a problem. However, if managers and customer contacts are not within the same domain it is probably better to add the person data twice - maybe the same person wants to have you different contact data as manager than as customer contact.
Part 2: You can choose what EF generates:
http://www.entityframeworktutorial.net/code-first/inheritance-strategy-in-code-first.aspx
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.