When to use and not to use inverse navigation property? [closed] - entity-framework

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 2 years ago.
Improve this question
It is obvious when to use a navigation property. But when should I use a inverse navigational property and when should I not use a inverse navigational property?
Should I always use a inverse navigation property when I use a navigation property to create a bi-directional relation?
Are there any guiding principles?

My guiding principle is to strive to keep things simple. I don't use them until I need them. :) Just like any other public member or method, (or any code for that matter) it should only exist if that existence is justified.
The presence of an inverse property indicates that I may treat that entity as a top-level and need to be able to refer to it's related entity. For example, a Customer contains Orders, so the question is should an Order reference back to it's Customer?
If I can query orders (irrespective of Customer) and want to be able to access customer information in those queries then it is beneficial to have an inverse property.
var orderDetails = context.Orders.Where(o => o.OrderDate == DateTime.Today)
.Select(o => new
{
o.OrderId,
o.OrderNumber,
CustomerName = o.Customer.Name
}).ToList();
As opposed to joining customer and order in a query to gain access to both customer and order details via a one-directional reference. (I tried writing an example from memory, but it got too ugly too fast. :D )
Where it doesn't make sense is to "always" have bi-directional references. For instance when you have something like an Address and an AddressType. AddressType will never need to know about a list of addresses of that type, and even if you did want to query that detail, it is easy enough to filter via the single-direction reference. It makes sense that Address (relative to the address type) is the top-level reference, where-as it makes sense that you may want to reference orders from a customer, or customer from an order.

They do not affect the generated sql. So from the point of view of database structure this is not important.
But when you are querying data from database by linq you can use that properties in "where" and "include" statements. So it gives you more options to create a query.
I'm almost always specifica inverse navigation property.

Related

MVVM in SwiftUI and the appropriate Bindings [closed]

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 1 year ago.
The community is reviewing whether to reopen this question as of 1 year ago.
Improve this question
Edited
Having multiple data sources for an app
What is the best approach to combine all data sources together in one class and add it as one environment object, keeping in mind data might change, therefore objects update the views?
What are the appropriate Bindings to use for:
Services (API fetches): #Published?
Computed variables: Lazy var?
Please refer to the diagram as an example. Thanks.
These questions were good references:
An equivalent to computed properties using #Published in Swift Combine?
https://medium.com/genetec-tech/property-wrappers-in-swift-5-1-the-missing-published-implementation-1a466ebcf660
diagram
So, you should use a layered architecture and you will not have those problems.
service layer, it's the lowest layer reads the data from either web or db, or other services
repository layer gets the data from service and process it, caching, etc
usecase layer combines data from multiple repositories
viewmodel layer gets the data from usecase and sends it to view
each service or repository handles one type of data "Users" for example
now, if you need to combine multiple types of data, like Users and Companies let's say, you need a Usecase layer which will combine all the data
on your viewmodel you only use the usecase layer
One important note, passed objects change between layers, so on service layer you have UserDto (coming from webservice), and UserEntity (coming from DB), the repo will transform those in UserResponse, which you don't know if it's db or webservice and even more the UseCase will transform UserResponse and CompanyReponse into a User object which will be passed to ViewModel and will contain all data required there.
Also, until you get to the viewmodel layer you should not need SwiftUI, if you need it, you are doing something wrong, use Swift Combine to handle data.

What is the best way to handle foreign keys with using type/subtype data model? [closed]

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 2 years ago.
Improve this question
I have to create a database structure for a (limited) set of products with some common and a lot of different attributes. I have created a main Product table/type, and for each subtype (Car, Bike) created a separate table. There is a foreign key reference of the product with unique constraint (one to one relation) in every subtype with also serves as a primary key in the subtype.
I have to refer products in other tables in a way that the target table can contain any one of the product types. For example, there is a contract table with the product as a foreign key in it. It can be any of subtype, (Car, Bike etc). How should I model these foreign keys?
I have two solutions in mind. I can create a reference in the contract table without FK constraint and also add another field to save to the subtype of the product (Polymorphic association). But I have to reference the product in a lot of places. I am afraid this approach will create an unmaintainable mess when used extensively.
The second solution is that I just reference the product supertype in every relationship and access subtype attributes from supertype because there will be one and only one subtype record for every supertype record.
I want to know how manageable is the second approach in the long run? What is the best way to join tables when I also need to fetch attributes of subtype while querying the product table?
I would use the second approach and create a foreign key to the product table wherever you need to reference "products" in general (not a specific product type).
If you do need the additional sub-type specific attributes when querying e.g. the contract table, you can always join to the sub-type tables or retrieve the additional attributes in a separate query. This depends on how often you need the specific attributes in the context where you just need "a product".
Depending on the requirements you have on the product specific attributes you might want to consider ditching the sub-type tables altogether and store the type specific attributes in a jsonb column in the product table. If you have really strong requirements with regards to data type checking or a fixed (and controlled) set of additional attributes, then this won't obviously work.
Questions like this one get asked from time to time, although usually the subtypes are particular to the case at hand.
You can view my usual answer here
noting that the term I used was superclass/subclass.
Your approach resembles Class Table Inheritance.
One technique that is worth a glance is Shared Primary Key. The subclasses don't have their own Id field. Instead, they use a copy of the Id field of the superclass table. This copy can function as a foreign key back to the superclass table and also ass the primary key of the subclass table. This makes some of the joins simple, easy, and fast.

Trying to understand and build a Core data model using relationships

So i have done some research on Core data relationships with Swift, and i have a base understanding of the functionality, but i wanted to see if i could get some help on my specific model. What i want to do is get a user inputted question and answer and have that pair or pairs of questions and answers be saved to Core Data under a name. For the model, i was thinking i need to create a Questions entity with an attribute question, an Answers entity with an attribute answer and a Name entity with an attribute name. This is where i get confused on how i can make this work, or if it is even a correct model in order a deck name to be given, questions and answers be input and saved to that name only. Each time a new name is created, i want the new questions and answers to be saved to that name and so on. Thanks in advance for any help that can be given.
Name -->> Question (one to many relationship)
Question --> Answer (one to one assuming there's just one answer per q)
Then you need to create reverse relationships for all of the above.
This is how it should look like in the editor:

What is the purpose of dynamic fields in MongoDB? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
At first, I thought it was pretty cool that you can add something to an object without it being defined in the model. But now I can't imagine how this is used in a web application like a Ruby on Rails application. What use cases require dynamic fields and how does the UI allow a user to define these dynamic fields? Do you let the user set the key for the dynamic field (with a text box or something)? Do any of you know off the top of your head any demos are applications in general that showcase the real usefulness of dynamic fields? Also, if you plan on reading these dynamic fields, wouldn't you need read_attribute (in the case of RoR) with the name of the "dynamic" field already planned for ahead of time?
I'm asking this question because I have an assignment in school to wrap an application around PostgreSQL and a NoSQL database (I chose MongoDB). I have successfully done this, however, every attribute that I add to any objects that I have defined on the MongoDB side is already defined in the model. I want to show that I'm aware of this capability, but I can't come up with any reason to use dynamic fields and I can't find results on the search, "purpose of dynamic fields in mongodb" or "dynamic fields mongodb demo".
Thanks!
First of all "Dynamic Field" is a Mongoid concept, and Mongoid is just a ODM to map ruby objects into MongoDB documents. MongoDB doesn't have and doesn't need a concept of Dynamic Fields since it is schemaless. Although this theoretically means that every document in a collection can have a different structure, this is never a practical application for a MongoDB.
An ODM such as Mongoid provides a useful mechanism to define a schema at the application level rather than in the database itself. In this context there are two big benefits to Dynamic Fields.
The ability to add sub documents that have varying structures. For example you can have an Animals collection. Each type of Animal could have different body parts. But in MongoDB I don't need a "tusks" column just because some animals have them.
The ability to change the schema without touching the database. It is very common to add functionality to a database through additional "columns". Using Mongoid/MondoDB this can happen in the application code, as easily as changing an application class -- completely transparently with respect to the database.
I think you took wrong aproach to asking/looking for answer to this question,in my opinion best answer will be from the source and here is a post from MongoDB blog, I hope it will help you out.
http://blog.mongodb.org/post/119945109/why-schemaless

Best Practice for Domain Entity Tracking Data? Base class or Composition? [closed]

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
One common aspect of most large projects is the need for common tracking data on many Domain Entities. For instance, most large projects, track the following properties for many Domain Entities:
DateTime DateCreated
User CreatedBy
DateTime LastModified
User LastModifiedBy
This data is pretty self explanatory, the data is used to track who did what when to a Domain object.
The question is what's the best way to handle this tracking data when designing the domain model for a large application.
The classic way is to use a base class and then have the relevant domain classes inherit from that base class. But this sets off my favor composition over inheritance alarm bell. The more large projects I've worked on, the more I reject inheritance out-of-hand, but that's not to say there are situations where it is the best option, perhaps in this case, for instance. An alternate inheritance solution would be to use an interface, but while this solution is less coupled, I don't see many examples using this approach on domain entities.
The second way would be to use composition to add a tracking object of sorts to each domain entity. The only problem with this is that the data-layer would have to be specifically instructed to not represent these as a separate table. A minor task, but one that is hard to justify if there is no pay-off.
The final way to handle tracking data is to configure the data-layer to do this transparently. I think it is probably possible to do this with Entity-Framework, but not having implemented this solution in the past, this would be the most upfront time intensive solution. It is difficult to foresee if this solution would be worth the trouble.
While this question may seem objective, this is actually a common task that most large projects have to deal with one way or another.
What is the best way to design a domain model and/or a large project for tracking metadata?
Best practice is often subjective and can cause as many problems as it solves. When should you inherit? When should you compose? Scholars spend years arguing the toss over the minutiae of a problem. Basic inheritance with a simple interface is pragmatic and effective. If it's a standard feature for all your entities then inheritance is probably the better option.
I have a base class with the audit properties and implemented an interface for these properties. I intercept the call to the context.SaveChanges() with the following code. It's simple and it works. It could be extended to fail if any tracked entity does not implement the IAudit interface.
public override int SaveChanges()
{
var entities = this.GetChangedAuditDataEntities();
foreach (var entity in entities)
{
this.SetModificationInfo(entity);
}
return base.SaveChanges();
}
private IEnumerable<IAuditData> GetChangedAuditDataEntities()
{
return (
from entry in _context.ChangeTracker.Entries()
where entry.State != EntityState.Unchanged
select entry.Entity)
.OfType<IAuditData>();
}
private void SetModificationInfo(IAuditData entity)
{
entity.lastModifiedBy = _currentUser.Name;
entity.lastModified = System.DateTime.Now;
}
This is one of those questions that does not automatically have a "correct" answer. If Jon Skeet were to answer it then it would be considered best practice. The only other correct answer will have to confirm your particular bias or at the every least strike the right intellectual note.
Years ago inheritance was rife and one of the many push backs from this has been the "value composition over inheritance" mantra. Fine, but inheritance has it's place.
I would suggest that any architectural layer that has many of the same type of object, such as a domain object (the words "domain object" imply common layer) can be greatly enhanced by having a common base class. System.Object is a good example of it. I'll give you another example. When we were defining the exception decorators for our solution we decided to extend the ToString() method to create a value that would uniquely identify the object.
public override string ToString()
{
if (this is IAuditData)
{
IAuditDataidentifiable = this as IAuditData;
return string.Format(#"{0} {{ id: {1}, ETag: {2} }}",
identifiable.GetType().Name,
identifiable.id,
identifiable.ETag);
}
else return base.ToString();
}
7 lines of code - pragmatic, simple and effective. From your question you sound wholly opposed to inheritance which must be borne from many a burnt finger. Me too ;-) but I still assert it's the better option in this instance.
I like what qujck has said in his answer and his comment but i would like to add something, if the tracking information represent an infrastructural concept i would go and put them in some infrastructure layer responsible for auditing or logging or etc .., otherwise if they are domain concepts i really like to keep them were they belong in the domain model layer and in this case i would use a complex object (value object) to represent them and to relief my self of the burden of setting them manually whenever i create a tracked object i would define a method that is called by my factory or IoC container whenever a tracked object is requested, my point is centralize change and keep concepts where they belong.