EF 4.2 Code First -- Image, Location, Product Entities Can't use list - entity-framework-4.1

I have product and location entities that may/may not have a collection of images.
I know I cannot create a list in the respective entities, but nor do I want to make an association in the Image entity for the other two.
I just want the Image Entity to have Id and file path.
Is there a way I can do this?
If the answer is I MUST create an association in the Image Entity for the other two, then that means whenever in the future I create a new entity that may/may not have photos, I have to modify the Image entity for the association and I do not like that idea.
Thanks in advance.

It sounds like you want a uni-directional relationship. Is this correct? So you want to access Collection<Image> from Product and Location, but not be able to access Product or Location from Image?
You can do this. In EF, the Image class will not have a navigational property to Product or Location -- it will just have Id and FilePath.
However in the database, the Image table will have columns for ProductId and LocationId. This is so that EF can manage the foreign key relationship and populate the collection propertes on Product and Location.
code:
modelBuilder.Entity<Product>.HasMany(p => p.Images).WithOptional()
.Map(d => d.MapKey("ProductId"));
modelBuilder.Entity<Location>.HasMany(p => p.Images).WithOptional()
.Map(d => d.MapKey("LocationId"));
When managing these in your application, you can just add images to the Images collection property on your principal entities (Product and Location) without having to set a navigation property from the dependent Image back to the principal (you can't since the foreign key properties are not present).

You could create two new tables, ProductImages and LocationImages, link to the collection from your Product and Locations, when you insert an item for either, insert a record that joins the image and the product.
That way, when you load your product or your location, you can check if there are any association images by checking the collection.

Related

Ccreating an entity relationship diagram in mysql

I want to create a database for my football (soccer) manager/training program:
I want it to store players and managers in the database, they will all have their own username and passwords etc. they should also have a position in which will be listed as an attribute along with their name, password etc.
Each position has different attributes (If possible I would want these to be stored in a separate table i.e. a goalkeeper table, a defender table, a midfielder table and a striker table), for example, a defender would have jockeying, clearing, heading, strength.
I'm using the MySqlite3 in python when creating these databases. I can figure out how to write the code once I know what structure my database (ERD) should be in.
My image shows the relationship between the different members of the team, however, my teacher and I both can't seem to figure out how to structure it
I would only create two entities because they share common attributes. I will merge the manger with player to team member and merge all the positions to position entity. the team_member has a postion_id as a foreign key.

it is better to make table for each individual column that has options or make options tuples inside model class in django

I am using Django 1.11 and mysql for a web database. I have table for cars ads post. This table has many columns such as title, price, time of the posted ads, and so on, there are many columns for car features like type, condition, cylinders, fuel. Each column of them has many choices. for example, for status there are choices of (excellent, very good, good, poor). For fuel gas, diesel. For cylinder choices are 3,4,5,6,8,12. And so on. I have two options to implement this.
1- The first option is to make table for cars contain columns that does not have options like title. Then connect this table to other tables (table for type, model, fuel, cylinders, and so on). Then connect each table to the main cars table in many to one relationship.
2- The second option is to make tuples inside Django model have these choices and make fields inside the main table instead of making every column individual table and then connect them through foreign key.
My question is that, which option is more effective from the prospective of:
1- Performance and speed
2- Easy to make forms, and to write and save to database the data comes up from the forms.
1- The first option is to make table for cars contain columns that does not have options like title. Then connect this table to other tables (table for type, model, fuel, cylinders, and so on). Then connect each table to the main cars table in many to one relationship.
I'm presuming that you want your models to be like this:
class CarCondition(models.Model):
condition_id = .. # the primary key, preferably an AutoField
condition_name = models.CharField(unique=True)
And then you would populate CarCondition like this:
condition_id | condition_name
1 | 'Excellent'
2 | 'Very good'
etc. And then in Car:
class Car(models.Model):
title = models.CharField()
...
condition = models.ForeignKey('CarCondition', on_delete=...)
...
The ModelForm:
class CarAdForm(forms.ModelForm):
class Meta:
model = Car
And that's it, because all the foreign keys are converted to ModelChoiceFields by Django.
You can save the data like this:
CarAdForm(req.POST).save()
in your view.
2- The second option is to make tuples inside Django model have these choices and make fields inside the main table instead of making every column individual table and then connect them through foreign key.
Since the columns like car_condition will have a tuple of choices, and will be a CharField, you will have to change a few things about the ModelForm, so that it can be rendered as a select widget. Refer as an example this answer. You may or may not require more than CarAdForm(req.POST).save() depending on what you change about the ModelForm.
It seems easier to create and save forms by the first approach. However, in my opinion, ForeignKey is more about referential integrity, whereas you are just trying to limit user input to a few choices, which is better done by the choices tuple.

Image urls in entity diagram

For a car retail system database, I will draw entity relationship diagram. I need a suggestion for keeping image urls as data.
For instance, should I define image attributes in every entities? Like;
In car model: carId carName carImage
In carSeller model: carSellerId carSellerName carSellerImage,
or
How should I define relation if it is defined as different entity? like:
in car model: carId carName ImageId(foreign)
in carSeller model: carSellerId carSellerName``ImageId(foreign)
in Image Model: ImageId ImageURL
or
Should I create different database? because there will be lots of entities that relates to image entity.
What is the best way doing it?
It depends on your task.
If you are going for One-to-One relation between image and car to give only one picture of the car, you can make image url a car's attribute, like in your 1st alternative.
If you want to give several images of one car, you are going for Many-to-One relation, and end up with table like (image_id,image_url,car_id (fk)). Another option is to use array datatype for car's images column, if your DBMS supports such feature.
And if you want to share pictures between similar cars, you need to implement a Many-to-Many relation with two tables: (image_id,image_url) plus (image_id (fk), car_id (fk)).

EF CodeFist Add rather than Update

I have two classes, one is Post and the other is Category, with a Many-to-Many relationship.
When i create a new Post business object, and a category object.
post.Categories.Add(category)
then using AutoMapper to map post from business model object to data entity,
when I do
dbContext.Posts.Add(post);
dbContext.SaveChanges();
it always add a new row to Categories table, even the category instance has value for ID, which is the key in database. Any one knows how to change this? if category info exists in database, then do nothing, except add a new row to CategpryPosts table
You need to attach the category to the context:
dbContext.Categories.Attach(category);
That tells EF it's an existing, unmodified entity.

Define a one-to-one relationship with LinqToSQL

I'm playing around with LinqToSQL using an existing multi-lingual database, but I'm running into issues mapping a fairly important one-to-one relationship, so I suspect I am using the feature incorrectly for my database design.
Assume two tables, Category and CategoryDetail. Category contains the CategoryId (PK), ParentId and TemplateId. CategoryDetail contains the CategoryId (FK), LanguageId, Title and Description (in the appropriate language), with a combined PK of CategoryId and LanguageId.
If I drag-and-drop these tables into the LinqToSQL designer, the resultant object model has Category with a collection of CategoryDetail objects, which should never be the case. I'd like to be able to filter on LanguageId at the DataContext level, meaning that the whole Category is encapsulated within Category.CategoryDetail, not all language version encapsulated within Category.CategoryDetails.
This database worked fine on my old object library (an old-school custom BOL and DAL), but I fear that LinqToSQL would require this to change in order to give me the required result.
What is the best way to make this relationship (and language filtering) as seamless as possible?
You can view properties of the association. (Right click on the line representing the association and show properties.) The properties will tell you if it is a one-to-one or one-to-many relationship. This is reflected in code by having either a single entity association (one-to-one) or an entity set association (one-to-many).
I would have to assume cant be a true 1 to 1. Sounds like you have a PK of CatID and Lang ID on the Cat Details table. That would explain why its putting a collection. I could be wrong as you didnt mention the PK's of the CatDetails table
EDIT: A combined Pk of CatID and Lang ID makes that a 1:m relationship, and Linq to SQL is actually doing the correct thing. The only way it could possibly be a true 1:1 is if you had a lang ID on the cat table as well and that was part of the FK. I htink you may have to rethink what you want to do, or how you want to implement it.
I think LINQ to SQL models the database structure directly.
You have two tables so it creates 2 objects.
Have you had a look at LINQ to Entities this allows you to create another layer above the database strucure to make for more readable classes.
Since you don't have a 1:1 relationship the mapping alone will not provide the desired functionality. However it is easy to provide a method in the parent auto-generated class that does the job:
public partial class Category
{
public IEnumerable<CategoryDetail> GetDetailsByLanguage(string langID)
{
return this.CategoryDetails.Where(c => c.LangID == langID);
}
}