Posts

Showing posts with the label entity-framework-core

Insert entity with one related entity which existed in the database

Insert entity with one related entity which existed in the database I am stuck at the operation when using Entity Framework Core 2 to perform an insert of a new entity with one related entity which already existed in the database. For example, I have two objects with one to many relationship: public Class OrderDetail { public int ParentID {get;set;} public string OrderDetailName {get;set;} public int ProductID {get;set;} public virtual Product ProductFK {get;set;} } public Class Product { public int ProductID {get;set;} public string ProductName {get;set;} public virtual Collection<OrderDetail> OrderDetails {get;set;} = new Collection<OrderDetail>(); } I would like to add a new OrderDetail with an existing Product (with productID = 3 ) into the database, so I perform like: OrderDetail Product productID = 3 private void AddOrderDetail(int productID) { OrderDetail newOrderDetail = new OrderDetail(); newOrderDetail.Name = "New OrderDetail...

EF Core DbContext Create Table for Custom Data Models

EF Core DbContext Create Table for Custom Data Models I would like to create database tables via instance of EntityFrameworkCore DbContext for custom data models which are not added to DdContext as DbSet property. Is that possible? Update: I would like to create a library that takes context and works with its own data model. Client project doesn't need to know library's data models[Context class doesn't have to dbset properties for custom models]. For example, aspnet core Identity. Library project uses a few database tables as I try to do, but dbcontext should inherit from IdentityDbContext. Thanks to this inheritance, DbContext has DbSet properties. If I use DbContext for custom data models, I don't need to extend DbContext class. Maybe explain the purpose behind it? Why would you want to do that? – NiQu Jun 30 at 8:58 ...