简体   繁体   中英

ASP Net Core Entity Framework entity creation from different tables

I am trying to create an OData Service using Entity Framework for ASP.NET Core.

First of all, I am kindly new to Entity Framework, but I have read a lot of articles related to this Topic. Unfortunately, some of them are not written well and furthermore most of them are not up to date or missing some key information. So I am going to ask you.

Current Situation:

I am trying to create a Model which combines values from two datatables of a datasource.

Let´s say we have the class Order and Article. Each order contains a bunch of articles. The objects can be mapped by the OrderID property which is stored in Order and Article.

So we have two lists containing every order and every article line in contract to the order

  • Order1 (0)
  • --> art1 (0)(0)
  • --> art2 (0)(1)
  • --> art3 (0)(2)
  • Order2 (1)
  • --> art1 (1)(0)

Of Course the orders and articles contains a lot of more properties, but in my test case I just would like to get the OrderID and the related article names.

public class OrderList
{
    public int OrderID { get; set; }
    public List<string> Article { get; set; }
}

I want to create a new Model called OrderList. In that model, I have the OrderID and a List of article Code (string)

I am getting the data from a database and need them to join into my new object OrderList.

Currently, I just got stuck by creating the Entity relationship. Do you guys have an idea to solve this properly?

  • ASP.NET Core 2.1
  • Microsoft.AspNetCore.OData (7.1.0)
  • Microsoft.EntityFrameworkCore (2.1.4)

What you want is implemented via navigation properties. When following the naming conventions , it is as easy as following:

public class Order
{
    public int OrderId { get; set; } // primary key
    public List<Article> Articles { get; set; } // navigation property
}

public class Article
{
    public int ArticleId { get; set; } // primary key
    public string Name { get; set; }

    public int OrderId { get; set; } // foreign key
    public Order Order { get; set; } // navigation property
}


public MyDbContext : DbContext
{
    public DbSet<Order> Orders { get; set; }
    public DbSet<Article> Articles { get; set; }
}

var foo = ctx.Orders.Include(e => e.Articles).ToList();

You can read more about ithere .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM