Does having a child with multiple one to one parents in a parent table make sense? Or would there be a more advantageous way to configure the relationship?
Ef core details:
Say I have a ProductSales table already, and I'd like to have a separate table that has a one to one with 2 ProductSales (for aggregating and comparing 2 product sales).
ProductSales
StoreId PK
ProductId PK
Date PK
SalesAmount
DailyChange
StoreId PK, FK1
ProductId PK, FK2
First Date FK1
Second Date FK2
AmmountDifference
Each ProductSales row will only be referenced once in the DailyChange table.
Does it make sense to have 2 one to one relationships between these 2 tables?
DailyChange --------- ProductSales1
DailyChange --------- ProductSales2
Daily Change builder:
builder.HasOne(b=> b.InitialProductSales)
.WithOne()
.HasForeignKey<DailyChange>(b => new { b.StoreId, b.ProductId, b.Date});
(and a similar one for the end date)
Related
I have 2 tables Center (centerId, name, address,...) and Student (StudentId, NAme, Address) and I determined they have a many-to-many relationship. As a result, I have created a new table CenterStudent (centerId, studentId,...) to join these 2 tables, and I set both centerId, studentId is PK and FK, and cascade delete.
Now I want to get all records with the same studentId. So I wrote
var lists = await studentCenterService.GetAsync(cancellationToken, studentId);
But I get an error
Entity type 'UserCenter' is defined with a 2-part composite key, but 1 values were passed to the 'DbSet.Find' method.
Could anyone give me a solution?
The error seems pretty clear - the .Find() method in EF works only on the complete PK - so if you have a PK made up from two columns (centerId, studentId), you cannot use .Find() to find all entries if you only supply studentId.
You need to use a
UserCenter.Where(x => x.studentId == studentId)
approach instead.
I want to stores many different products in my database(as well as in one table). With help of inheritance (Table per Concrete Type) ,i am keeping all common fields(date,customer,orderID) in parent table and made one child table for one product .
one child table => it holds many different product with same and different fields
ProductOne = {A,B,**C**}
ProductTwo = {A,B,**D**}
ProductThree ={A,B,**F**}
Now i made TableAllProduct and Field of tables are {A,B,C,D,F}
To reason to select this design ,because i am thinking about my future new product ,For example if we got new product with these exist fields{A,B,C,D,F} ,so we should able to store new product data in TableAllProduct table without any software upgrade (instead create new table as per Inheritance approach which required new code)
TableAllProduct can hold three different product ProductOne = {A,B,C} ProductTwo = {A,B,D} ProductThree ={A,B,F}
Next step is stores Data in TableAllProduct
As per given scenario, ProductOne and ProductTwo have common field {A,B} But A field stores data from ProductOne as well as for ProductTwo
ProductOne have following option=={data__A_1,data__A_2 ,data__A_3}
ProductTwo have following option =={data__B_1,data__B_2 }
which i brings from other table (Manny to Manny)
Here we breaks rules of RDBMS ,Because I need multiple foreign key at one column ,But RDBMS doesn't supports , To delete/edit of foreign key responsibilities/function can done with DELETE_trigger(which will check record in Category table )
In this way , i can stores multiple product in table for now and future.
What is disadvantage of this approach ?
Is there any other possibilities solutions to solve this problem with better way .(I know about Entity–attribute–value model ,but in our situation ,product doesn't not changes daily /weekly bases and EVA is too complex to maintain).Thanks
You need to normalize your data.
The model you've described can work. You need to have the AllProducts table only contain the attributes(columns) in common for all of the products. Attributes like name and SKU, and maybe a reference to the vendor/supplier.
Once you have identified the common attributes, the remaining attributes can be moved into a table specific to each product. The SpecificProduct table can use the PK of the AllProducts table as a PK and FK. Every record in SpecificProduct will also have a record in the AllProducts table. The complete data for a specific product consists of the attributes from the AllProducts table joined to the columns for the specific product table.
This strategy helps to keep the AllProducts table width small when a varied subset of attributes relates to a small subset of the records in the table. By reusing the AllProducts PK as the PK/FK of the specific products table, you ensure joins performance will be good as well.
I am creating a database which is similar to the following situation.
Table1:
CustomerType1 (Column: CustomerId,...)
Table2:
CustomerType2 (Column: CustomerId,...)
Table 3:
Orders (Columns: OrderId, CustomerId...)
Now, how can I relate the customerId of orders table to customerId column of CustomerType1 and CustomerType2 tables?
(I am working on a windows phone app, so if you can help me with the attributes used in creating a database similar to above situation than it would be helpful)
Thanks
Your database should be composed of 4 tables:
- Customer(CustomerId, common stuff to all customers)
- CustomerType1(CustomerId, specific stuff to type 1 customers)
- CustomerType2(CustomerId, specific stuff to type 2 customers)
- Orders(OrderId, CustomerId, other order stuff)
The table columns CustomerType1.CustomerId and CustomerType2.CustomerId provide a reference to the Customer table by means of the Customer.CustomerId column. Also a reference to the Orders table and Customer table can be achieved by using the Orders.CustomerId and Customer.CustomerId columns.
For clarity, the tables CustomerType1, CustomerType2 and Orders would all have a Foreign key constraint as following:
FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId)
I am quite new to EDMs, having written quite a lot of ADO.Net stuff in the past. I have three tables:
**Product:**
Prod_ID - PK
**Product_MaxLoan**
Prod_ID - PK
**Product_MinLoan**
Prod_ID - PK
These tables, hosted in MS SQL 2005, have no FKs or constraints configured as yet, they are to have a notional 1 to 1 relationship. For example, every row of a Product with ID of 1, there will be a row in Product_MaxLoan and Product_MinLoan each with an ID of 1.
In Visual Studio 2010, I want to set the EDM up correctly so that the cardinality is set to 1 to 1. I previously had FK constraints on the tables and the following set up, however, this would only allow a 0..1 cardinality (to cater, I suppose, for the fact a Product may not have a Product_MaxLoan or Product_MinLoan).
**Product:**
Prod_ID - PK
**Product_MaxLoan**
ID - PK
Prod_ID - FK
**Product_MinLoan**
ID - PK
Prod_ID - FK
Questions:
What advice would you give for setting these tables up in SQL 2005? For a 1 to 1 relationship in an EDM would you set up FKs?
Can you set up a PK relationship in SQL 2005 that the EDM will read when importing from a database?
A product contains some 300 properties, so containing all of this
data in a single table would be poor database normalization (hence
the many 1 - 1 tables). Would best practice be to put all of these
properties into a single EDM class? My gut reaction is to break it
down much as it is structured in the DB (this is my ADO heritage
coming to the fore), having a class for each logical part of the
product.
Your advice would be appreciated.
Best regards,
Mark
In database use this configuration:
**Product:**
Prod_ID - PK
**Product_MaxLoan**
Prod_ID - PK, FK (to Product)
**Product_MinLoan**
Prod_ID - PK, FK (to Product)
This will force one-to-one relation on database level as well as in EF. The relation itself will be 1 - 0..1 (Product can exists without MaxLoan and MinLoan) because real 1 : 1 cannot exist in database. Real 1 : 1 demands that both entities always exists = you cannot insert the first if the second doesn't exist and you cannot insert the second if the first doesn't exists. How do you insert them without turning off referential integrity?
I'm trying to take an object and design an SQL table to store it. The object has a member called "Roles" which is an enum that has 4 values. Each object can have several different roles.
Right now, I've taken the enum and created an eponymously named SQL table out of it and added the 4 roles to it. Now I'm trying to design the object table and I can't figure out how to get the many to many relationship working for it. I would also like it to work well with Linq-to-SQL. It would be nice to have the enum preserved, but if not an array of strings could also work.
In short, I need a table that has a many-to-many between Roles and Object.Roles (or Object.Roles[])
Thanks!
Generally, Many-To-Many relationships in Linq2SQL (and Entity Framework) are created by introducing an association table, with only the primary keys from the two tables you want to link, and where each row corresponds to an association.
Since your Role and Object.Role could be difficult to keep apart in an attempt to explain this, I'll give another example: in a school, each teacher can have many students, and each student can have many teachers. The table structure to represent this would then be
Teachers Students StudentTeacherRelations
******** ******** ***********************
TeacherId StudentId TeacherId
FirstName FirstName StudentId
etc... etc...
Now, Linq2SQL and EF are both smart enough to recognize this as a many-to-many relationship, and introduce navigation properties in your model. A POCO with appropriate properties for the Student object could look like this:
public class Student
{
public int StudentId { get; set; }
public string FirstName { get; set; }
// etc
public IEnumerable<Teacher> Teachers { get; }
}
If this is set up correctly, the O/R mapper will automatically populate the Teachers property.
Update: In response to comments, here is a how I'd structure the rest of the database if I wanted to include a scenario where each teacher can give some students homework consisting of a number of questions:
HomeworkAssignments Questions Answers
******************* ********* *******
HomeworkAssignmentId (pk) QuestionId (pk) AnswerId (pk)
... HomeworkAssignmentId (fk) QuestionId (fk)
... StudentId (fk)
...
StudentHomeworkAssignmentRelations TeacherHomeworkAssignmentRelations
********************************** **********************************
StudentId (fk) Teacherid (fk)
HomeworkAssignmentId (fk) HomeworkAssignmentId (fk)
As you can see, there's quite a lot of tables here. However, this structure allows you to let each teacher create many homework assignments, and then hand each assignment out to a number of students. You'll have a navigational property Student.HomeworkAssignments of type IEnumerable<HomeworkAssignment>, via which you can find all the questions a student has to answer. For each posted answer, you store a row in the Answers table, which is linked to both questions and students by 1-to-many relations - each answer can belong to one question only, and be given by one student only.
The key here is that you don't need to be able to access each answer given by a student directly - in both Linq2SQL and EF it's possible to request data from many tables at once in various ways. One of those ways is
var answersToTheLastExam = context.Students
.SelectMany(s => s.HomeworkAssignments)
.OrderBy(ha => ha.Date) // this might need modifying to get the last one first
.First(ha => ha.Questions.Count() > 0)
.SelectMany(ha => ha.Questions)
.SelectMany(q => q.Answers)
.Where(a => a.StudentId == myId)
Note that this code is untested an might not work as I say it will. I'm just trying my best off the top of my head here =)
Roles
Id Pk
ObjectRoles
Id Pk
ObjectRoleRoles
RolesId Pk & FK
ObjectRolesId PK & FK
var result = (from orr in _context.ObjectRoleRoles
inner join r in _context.Roles on orr.RolesId equals r.Id
inner join or in _context.ObjectRoles on orr.ObjectRolesId equals or.Id
where orr.RolesId equals 1
select r).ToList();
The fields in ObjectRoleRoles must be both the PK and FK.