EF Core - Mapping Many-to-One - entity-framework

I'm trying to create a mapping between the 2 tables using EF Core Data Annotation.
So here's my sample scenario. Let's suppose I have theses classes that consist of following properties
Orders
[Key]
public int OrderId {get;set}
public string OrderNumber {get;set;}
OrderStatuses
[Key]
public int OrderStatusId {get;set}
public string OrderNumber {get;set;}
public StatusEnum Status {get;set} // Pending, Delivered, Cancel
I have this example data:
OrderId OrderNumber // Order Table
1 11111
2 11111
3 11111
4 22222
OrderStatusId OrderNumber Status
1 11111 Pending
2 22222 Pending
Basically, I created OrderStatuses table that stores the status of the OrderNumber but they have no relationship since I have no idea how to make them Many-to-One using Data Annotation of Entity Framework Core without using the key. I want to achieve this so I can use the .Include method in fetching all the info.
The key is, Many Orders but One Status only. I hope somebody helps me.

As you are wanting many-to-one between Order and OrderStatus, It seems you have configured your model relation wrongly.
So your OrderStatus and Order model class should be as follows:
public class OrderStatus
{
[Key]
public int OrderStatusId { get; set; }
public StatusEnum Status { get; set; }
public ICollecton<Order> Orders {get; set;}
}
public class Order
{
[Key]
public int OrderId { get; set; }
public string OrderNumber { get; set; }
public OrderStautsId {get;; set;}
public OrderStatus OrderStatus { get; set; }
}

Related

Make one-to-one relation to many tables in EF

I want to have one table with pictures for many other objects, lets say for Meals, Ingridents, ...
One Picture is for particular class (say Meal). This way I could have many tables with PictureId as FK, but can't apply this 2nd data annotation attribute.
public class Picture
{
[Key, ForeignKey("Ingridient"), ForeignKey("Meal")] //<---here I get error
public int PictureId { get; set; }
//properties
public byte[] PictureData { get; set; }
public string Name { get; set; }
[Required]
public virtual Ingridient Ingridient { get; set; } //1 - 1
[Required]
public virtual Meal Meal { get; set; } //1 - 1
}
I think I don't follow convention but please tell me how to fix it.
Why PictureId can't be a FK in many tables (Meals, Ingridients, ...)
I could have many tables with PictureId as FK
Then those other Entities should have the Foreign Key properties and Navigation Properties.
eg
public class Meal
{
public int MealId {get;set;}
// ...
public int? PictureId {get;set;}
public virtual Picture Picture {get;set;}
}

Entity Framework : Code First Approach. Creating Entities using TPT inheritance

I am new to entity framework and I am using code first approach to create entities using TPT inheritance.
My requirement is to create the entities as per the attached diagram where ID is PK for Customers table and FK for the AddressDetails and ContactDetails table. Based on the keys I also need to create the association and navigation properties for the entities. Table Diagram
In my code I have created entities as
public class Customer
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int ZipCode { get; set; }
public virtual ContactDetails ContactDetails { get; set; }
public virtual AddressDetails AddressDetails { get; set; }
}
[Table("ContactDetails")]
public class ContactDetails: Customer
{
public string MobileNo { get; set; }
public string EmailId { get; set; }
}
[Table("AddressDetails")]
public class AddressDetails: Customer
{
public string BillingAddress { get; set; }
public string DeliveryAddress { get; set; }
}
My question is, have I created the association and navigation properties correctly or do I need to add them in the ContactDetails and AddressDetails class as well? Also, when I run the code the entities are getting created in the database but for the Customer table there are 2 additional columns created as AddressDetails_Id(FK,int,null) and ContactDetails_Id(FK,int,null). I think they are created because of the navigation property but I do not need these columns in the database to be created. Also the values are always null in these two columns.
Any help would be appreciated. Thanks in advance.

Data Migration Code First Table order is alphabetical

The class have properties ordered in the way it makes sense e.g.
public int Id { get; set; }
public string Name{ get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
public Address {get; set;}
public City {get; set;}
[Timestamp]
public byte[] RowStamp { get; set; }
After running data migration the table is generated with columns in sorted order.
The table generated has Id column followed by City and so on. I like to keep the order of the class
Is there any way to avoid reordering columns while data migration?
You can specify an order using Column Attributes (i.e. DataAnnotations), but I will warn you that it can become troublesome to maintain (too troublesome, IMO). Still, here's what it looks like:
[Column("Id" , Order = 1)]
public int Id { get; set; }
Check out Ordering Column Attributes in Entity Framework

How to map multiple tables into one Entity in EF7

I have 2 tables in different schemas:
Base.Person
ID
FirstName
LastName
Enrollment.Student
PersonID
StudentNo
This is related one-to-one.
Now in my DbContext, I want to have a DbSet named Students but I want its properties mapped to Person and Students. In particular, I want to get Person.ID, Person.FirstName, Person.LastName, Student.StudentNo mapped into my Student class.
The Student class is:
public class Student
{
public int ID { get; set;}
public string FirstName { get; set;}
public string MiddleName { get; set;}
public string StudentNo { get; set;}
}
One additional question that I'd like to ask which is not related to my problem above but it will be clearer to ask if the example above is present, in designing your DbContext, is DbContext intended to make the whole of the database available to you or is it ok just to expose what you want? For example, in my question above, I don't have a Person DbSet.
You cannot currently do this in EF 7 EF Core. However, you can model one to one relationships like this:
[Table("Student", Schema = "Enrollment")]
public class Student
{
[Key]
public string StudentNo { get; set; }
[ForeignKey("PersonId")]
public Person Person { get; set; }
[Column("PersonID")] // <-- if your db is case sensitive
public int PersonId { get; set; }
}
[Table("Person", Schema="Base")]
public class Person
{
// [Key] - not needed as EF conventions will set this as the "key"
[Column("ID")] // again, if case sensitive
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
// in code, use .Include to materialize dependent entities like so....
context.Students.Include(s => s.Person).Where(s => s.Person.FirstName == "Bob");
For more info on modeling, see https://docs.efproject.net/en/latest/modeling/relationships.html#one-to-one

EF 4.1 Code First - Self-referencing foreign keys and Foreign key to other tables

I have a POCO class as follows
public class Category
{
public int ID {get; set; }
public string desc {get; set; }
public int parentID {et; set; }
}
public class Issue
{
public int ID {get; set;}
....
public int categoryID {get; set; }
public int subCategoryID {get; set; }
public virtual Category category{get; set; }
public virtual Category subCategory {get; set;}
}
I keep getting errors with foreign keys with the above classes. Basically, my Category table holds categories with sub categories. And an issue can have a category and subCategory. Would somebody guide me to the correct way to define this relationship? I've tried using Foreign Key annotations but it gives me an error saying the data base was created but the object creation failed because of foreign key relation specified on Issue. Any ideas why? And what I can do to resolve this ?
Please see this article - How to Configure a Self Referencing Entity in Code First
I believe that will help you setup the relationship correctly. As you will see in the article you need to define some addditional fluent settings in the OnModelCreating method in your DbContext class.
You can do this with a single class.
For EF4.1 Code first I have the following example:
/// <summary>
/// represents a single configuration item within CM
/// </summary>
public class CI
{
[Key]
public int ID { get; set; }
....
[ForeignKey("Parent")]
public int? Parent_ID { get; set; }
[InverseProperty("Parent")]
[ForeignKey("Parent_ID")]
public virtual ICollection<CI> Contents { get; set; }
[InverseProperty("Contents")]
public virtual CI Parent { get; set; }