Entity Framework nested joinsEntity Framework Join 3 TablesEntity Framework vs LINQ to SQLHow do I view the SQL generated by the Entity Framework?How can I get Id of inserted entity in Entity framework?Fastest Way of Inserting in Entity FrameworkEntity Framework support for old database that uses -1 to indicate no relationship?ADO.NET Entity Framework - Recreate entity class painlessly?Entity Framework - “eager loading” using .Include() and .Select() - how to use a LEFT JOIN rather than INNER JOIN?No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'How do I map a C# int to a SqlServer tinyint using Entity Framework Code First?Entity Framework HasForeignKey not working
While drilling into kitchen wall, hit a wire - any advice?
Scaling rounded rectangles in Illustrator
If studying in groups is more effective, why don't academics also research in groups?
why it is 2>&1 and not 2>>&1 to append to a log file
Translation of "invincible independence"
My parents are Afghan
Drug Testing and Prescribed Medications
Why is the episode called "The Last of the Starks"?
Why was Gemini VIII terminated after recovering from the OAMS thruster failure?
Picking a theme as a discovery writer
How large is a Globe of Invulnerability cast by a Large creature?
Is there any optimization for thread safety in for loop of Java?
call() a function within its own context
Why is the blank symbol not considered part of the input alphabet of a Turing machine?
How to increase speed on my hybrid bike with flat handlebars and 700X35C tyres?
What's weird about Proto-Indo-European Stops?
Router cannot connect to Internet
How to make a kid's bike easier to pedal
I want to write a blog post building upon someone else's paper, how can I properly cite/credit them?
Explaining intravenous drug abuse to a small child
My large rocket is still flipping over
What does the copyright in a dissertation protect exactly?
cd ` command meaning and how to exit it?
What does “two-bit (jerk)” mean?
Entity Framework nested joins
Entity Framework Join 3 TablesEntity Framework vs LINQ to SQLHow do I view the SQL generated by the Entity Framework?How can I get Id of inserted entity in Entity framework?Fastest Way of Inserting in Entity FrameworkEntity Framework support for old database that uses -1 to indicate no relationship?ADO.NET Entity Framework - Recreate entity class painlessly?Entity Framework - “eager loading” using .Include() and .Select() - how to use a LEFT JOIN rather than INNER JOIN?No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'How do I map a C# int to a SqlServer tinyint using Entity Framework Code First?Entity Framework HasForeignKey not working
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am new to entity framework and am having a hard time trying to figure out how to query with a join when my models look like this (drastically simplified)
class Customer
public int Id get; set;
public Vehicles Vehicles get; set;
class Vehicles
public List<Vehicle> Items get; set;
class Vehicle
public int Id get; set;
public int CustomerId get; set;
If I put the List<Vehicle> on the customer class directly. I am able to do fluent mapping like this
builder.Entity<Customer>()
.HasMany(x => x.Items)
.WithOne()
.HasForeignKey(x => x.CustomerId);
Which then I can do this and I get back a customer object with vehicles
db.Customers.Include(x => x.Items).FirstOrDefault(x => x.Id == 1);
What I am not understanding is how to do this with my original set of models. I would like to keep them the way they are if possible. I have tried doing various versions of this in my onModelCreating method with no luck.
builder.Entity<Customer>(t =>
t.OwnsOne(x => x.Vehicles, v =>
v.HasMany(x => x.Items).WithOne().HasForeignKey(x => x.CustomerId);
);
);
entity-framework .net-core
add a comment |
I am new to entity framework and am having a hard time trying to figure out how to query with a join when my models look like this (drastically simplified)
class Customer
public int Id get; set;
public Vehicles Vehicles get; set;
class Vehicles
public List<Vehicle> Items get; set;
class Vehicle
public int Id get; set;
public int CustomerId get; set;
If I put the List<Vehicle> on the customer class directly. I am able to do fluent mapping like this
builder.Entity<Customer>()
.HasMany(x => x.Items)
.WithOne()
.HasForeignKey(x => x.CustomerId);
Which then I can do this and I get back a customer object with vehicles
db.Customers.Include(x => x.Items).FirstOrDefault(x => x.Id == 1);
What I am not understanding is how to do this with my original set of models. I would like to keep them the way they are if possible. I have tried doing various versions of this in my onModelCreating method with no luck.
builder.Entity<Customer>(t =>
t.OwnsOne(x => x.Vehicles, v =>
v.HasMany(x => x.Items).WithOne().HasForeignKey(x => x.CustomerId);
);
);
entity-framework .net-core
why do you have an entity vehicles as a container for a list of vehicles? That does not sound clean. If that's what you BO's look like, you should consider converting them into model objects to save one table and the one-to-one relationship. Also, you may consider either exposing or hiding all FK properties to be consistent.
– DevilSuichiro
Mar 23 at 9:26
This is unusual model, so it's not surprising that it's problematic to be mapped. The wayVehiclesclass is defined in the example (w/o additional properties) it makes no sense. In order to try helping, we need to know the meaning ofVehiclesclass - is it an entity (and if yes, does it have its own table or has to be stored in theCustomertable) or just a some sort of a container class?
– Ivan Stoev
Mar 23 at 13:44
It is a container class. It does not have its own table. The two tables involved in this are a customers table and a vehicles table. I'm attempting to reuse a large set of entities that exist in this solution. They aren't exactly representative of the database but are very close. I've been able to make the rest of it work with fluent mapping.
– Jacob
Mar 23 at 13:52
add a comment |
I am new to entity framework and am having a hard time trying to figure out how to query with a join when my models look like this (drastically simplified)
class Customer
public int Id get; set;
public Vehicles Vehicles get; set;
class Vehicles
public List<Vehicle> Items get; set;
class Vehicle
public int Id get; set;
public int CustomerId get; set;
If I put the List<Vehicle> on the customer class directly. I am able to do fluent mapping like this
builder.Entity<Customer>()
.HasMany(x => x.Items)
.WithOne()
.HasForeignKey(x => x.CustomerId);
Which then I can do this and I get back a customer object with vehicles
db.Customers.Include(x => x.Items).FirstOrDefault(x => x.Id == 1);
What I am not understanding is how to do this with my original set of models. I would like to keep them the way they are if possible. I have tried doing various versions of this in my onModelCreating method with no luck.
builder.Entity<Customer>(t =>
t.OwnsOne(x => x.Vehicles, v =>
v.HasMany(x => x.Items).WithOne().HasForeignKey(x => x.CustomerId);
);
);
entity-framework .net-core
I am new to entity framework and am having a hard time trying to figure out how to query with a join when my models look like this (drastically simplified)
class Customer
public int Id get; set;
public Vehicles Vehicles get; set;
class Vehicles
public List<Vehicle> Items get; set;
class Vehicle
public int Id get; set;
public int CustomerId get; set;
If I put the List<Vehicle> on the customer class directly. I am able to do fluent mapping like this
builder.Entity<Customer>()
.HasMany(x => x.Items)
.WithOne()
.HasForeignKey(x => x.CustomerId);
Which then I can do this and I get back a customer object with vehicles
db.Customers.Include(x => x.Items).FirstOrDefault(x => x.Id == 1);
What I am not understanding is how to do this with my original set of models. I would like to keep them the way they are if possible. I have tried doing various versions of this in my onModelCreating method with no luck.
builder.Entity<Customer>(t =>
t.OwnsOne(x => x.Vehicles, v =>
v.HasMany(x => x.Items).WithOne().HasForeignKey(x => x.CustomerId);
);
);
entity-framework .net-core
entity-framework .net-core
asked Mar 23 at 5:58
JacobJacob
840617
840617
why do you have an entity vehicles as a container for a list of vehicles? That does not sound clean. If that's what you BO's look like, you should consider converting them into model objects to save one table and the one-to-one relationship. Also, you may consider either exposing or hiding all FK properties to be consistent.
– DevilSuichiro
Mar 23 at 9:26
This is unusual model, so it's not surprising that it's problematic to be mapped. The wayVehiclesclass is defined in the example (w/o additional properties) it makes no sense. In order to try helping, we need to know the meaning ofVehiclesclass - is it an entity (and if yes, does it have its own table or has to be stored in theCustomertable) or just a some sort of a container class?
– Ivan Stoev
Mar 23 at 13:44
It is a container class. It does not have its own table. The two tables involved in this are a customers table and a vehicles table. I'm attempting to reuse a large set of entities that exist in this solution. They aren't exactly representative of the database but are very close. I've been able to make the rest of it work with fluent mapping.
– Jacob
Mar 23 at 13:52
add a comment |
why do you have an entity vehicles as a container for a list of vehicles? That does not sound clean. If that's what you BO's look like, you should consider converting them into model objects to save one table and the one-to-one relationship. Also, you may consider either exposing or hiding all FK properties to be consistent.
– DevilSuichiro
Mar 23 at 9:26
This is unusual model, so it's not surprising that it's problematic to be mapped. The wayVehiclesclass is defined in the example (w/o additional properties) it makes no sense. In order to try helping, we need to know the meaning ofVehiclesclass - is it an entity (and if yes, does it have its own table or has to be stored in theCustomertable) or just a some sort of a container class?
– Ivan Stoev
Mar 23 at 13:44
It is a container class. It does not have its own table. The two tables involved in this are a customers table and a vehicles table. I'm attempting to reuse a large set of entities that exist in this solution. They aren't exactly representative of the database but are very close. I've been able to make the rest of it work with fluent mapping.
– Jacob
Mar 23 at 13:52
why do you have an entity vehicles as a container for a list of vehicles? That does not sound clean. If that's what you BO's look like, you should consider converting them into model objects to save one table and the one-to-one relationship. Also, you may consider either exposing or hiding all FK properties to be consistent.
– DevilSuichiro
Mar 23 at 9:26
why do you have an entity vehicles as a container for a list of vehicles? That does not sound clean. If that's what you BO's look like, you should consider converting them into model objects to save one table and the one-to-one relationship. Also, you may consider either exposing or hiding all FK properties to be consistent.
– DevilSuichiro
Mar 23 at 9:26
This is unusual model, so it's not surprising that it's problematic to be mapped. The way
Vehicles class is defined in the example (w/o additional properties) it makes no sense. In order to try helping, we need to know the meaning of Vehicles class - is it an entity (and if yes, does it have its own table or has to be stored in the Customer table) or just a some sort of a container class?– Ivan Stoev
Mar 23 at 13:44
This is unusual model, so it's not surprising that it's problematic to be mapped. The way
Vehicles class is defined in the example (w/o additional properties) it makes no sense. In order to try helping, we need to know the meaning of Vehicles class - is it an entity (and if yes, does it have its own table or has to be stored in the Customer table) or just a some sort of a container class?– Ivan Stoev
Mar 23 at 13:44
It is a container class. It does not have its own table. The two tables involved in this are a customers table and a vehicles table. I'm attempting to reuse a large set of entities that exist in this solution. They aren't exactly representative of the database but are very close. I've been able to make the rest of it work with fluent mapping.
– Jacob
Mar 23 at 13:52
It is a container class. It does not have its own table. The two tables involved in this are a customers table and a vehicles table. I'm attempting to reuse a large set of entities that exist in this solution. They aren't exactly representative of the database but are very close. I've been able to make the rest of it work with fluent mapping.
– Jacob
Mar 23 at 13:52
add a comment |
2 Answers
2
active
oldest
votes
It's possible to map the original classes, but in quite counterintuitive way.
Since the Vehicles class is just a container, mapping it as owned entity as you have tried seems the most natural way. However currently EF Core does not allow owned entity to be at the principal side of the relationship, and in your case this is needed.
So instead you need to map the Vehicles class as regular "entity" sharing the same table with the Customer - the so called table splitting. You have to do explcitly all that EF Core does implicitly for owned entities - define a shadow property and map is a both PK and FK for the one-to-one relationship with the Customer. You'd need also the explicitly map the Vehicle.CustomerId as a FK because from EF point of view the Vehicle is related to Vehicles rather than to Custome, hence the conventional FK property / column name assumed will be VehiclesId. Note that with this model you'll never be able to define an inverse navigation property Customer of the Vehicle.
With that being said, here is the fluent configuration needed:
modelBuilder.Entity<Vehicles>(builder =>
// Table
builder.ToTable(modelBuilder.Entity<Customer>().Metadata.Relational().TableName);
// PK
builder.Property<int>("Id");
builder.HasKey("Id");
// One-to-one relationship with Customer
builder.HasOne<Customer>()
.WithOne(e => e.Vehicles)
.HasForeignKey<Vehicles>("Id");
// One-to-many relationship with Vehicle
builder.HasMany(e => e.Items)
.WithOne()
.HasForeignKey(e => e.CustomerId);
);
and usage:
db.Customers
.Include(x => x.Vehicles.Items) // <--
// ...
add a comment |
Use .Join
See this question for some examples:
Entity Framework Join 3 Tables
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55311063%2fentity-framework-nested-joins%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
It's possible to map the original classes, but in quite counterintuitive way.
Since the Vehicles class is just a container, mapping it as owned entity as you have tried seems the most natural way. However currently EF Core does not allow owned entity to be at the principal side of the relationship, and in your case this is needed.
So instead you need to map the Vehicles class as regular "entity" sharing the same table with the Customer - the so called table splitting. You have to do explcitly all that EF Core does implicitly for owned entities - define a shadow property and map is a both PK and FK for the one-to-one relationship with the Customer. You'd need also the explicitly map the Vehicle.CustomerId as a FK because from EF point of view the Vehicle is related to Vehicles rather than to Custome, hence the conventional FK property / column name assumed will be VehiclesId. Note that with this model you'll never be able to define an inverse navigation property Customer of the Vehicle.
With that being said, here is the fluent configuration needed:
modelBuilder.Entity<Vehicles>(builder =>
// Table
builder.ToTable(modelBuilder.Entity<Customer>().Metadata.Relational().TableName);
// PK
builder.Property<int>("Id");
builder.HasKey("Id");
// One-to-one relationship with Customer
builder.HasOne<Customer>()
.WithOne(e => e.Vehicles)
.HasForeignKey<Vehicles>("Id");
// One-to-many relationship with Vehicle
builder.HasMany(e => e.Items)
.WithOne()
.HasForeignKey(e => e.CustomerId);
);
and usage:
db.Customers
.Include(x => x.Vehicles.Items) // <--
// ...
add a comment |
It's possible to map the original classes, but in quite counterintuitive way.
Since the Vehicles class is just a container, mapping it as owned entity as you have tried seems the most natural way. However currently EF Core does not allow owned entity to be at the principal side of the relationship, and in your case this is needed.
So instead you need to map the Vehicles class as regular "entity" sharing the same table with the Customer - the so called table splitting. You have to do explcitly all that EF Core does implicitly for owned entities - define a shadow property and map is a both PK and FK for the one-to-one relationship with the Customer. You'd need also the explicitly map the Vehicle.CustomerId as a FK because from EF point of view the Vehicle is related to Vehicles rather than to Custome, hence the conventional FK property / column name assumed will be VehiclesId. Note that with this model you'll never be able to define an inverse navigation property Customer of the Vehicle.
With that being said, here is the fluent configuration needed:
modelBuilder.Entity<Vehicles>(builder =>
// Table
builder.ToTable(modelBuilder.Entity<Customer>().Metadata.Relational().TableName);
// PK
builder.Property<int>("Id");
builder.HasKey("Id");
// One-to-one relationship with Customer
builder.HasOne<Customer>()
.WithOne(e => e.Vehicles)
.HasForeignKey<Vehicles>("Id");
// One-to-many relationship with Vehicle
builder.HasMany(e => e.Items)
.WithOne()
.HasForeignKey(e => e.CustomerId);
);
and usage:
db.Customers
.Include(x => x.Vehicles.Items) // <--
// ...
add a comment |
It's possible to map the original classes, but in quite counterintuitive way.
Since the Vehicles class is just a container, mapping it as owned entity as you have tried seems the most natural way. However currently EF Core does not allow owned entity to be at the principal side of the relationship, and in your case this is needed.
So instead you need to map the Vehicles class as regular "entity" sharing the same table with the Customer - the so called table splitting. You have to do explcitly all that EF Core does implicitly for owned entities - define a shadow property and map is a both PK and FK for the one-to-one relationship with the Customer. You'd need also the explicitly map the Vehicle.CustomerId as a FK because from EF point of view the Vehicle is related to Vehicles rather than to Custome, hence the conventional FK property / column name assumed will be VehiclesId. Note that with this model you'll never be able to define an inverse navigation property Customer of the Vehicle.
With that being said, here is the fluent configuration needed:
modelBuilder.Entity<Vehicles>(builder =>
// Table
builder.ToTable(modelBuilder.Entity<Customer>().Metadata.Relational().TableName);
// PK
builder.Property<int>("Id");
builder.HasKey("Id");
// One-to-one relationship with Customer
builder.HasOne<Customer>()
.WithOne(e => e.Vehicles)
.HasForeignKey<Vehicles>("Id");
// One-to-many relationship with Vehicle
builder.HasMany(e => e.Items)
.WithOne()
.HasForeignKey(e => e.CustomerId);
);
and usage:
db.Customers
.Include(x => x.Vehicles.Items) // <--
// ...
It's possible to map the original classes, but in quite counterintuitive way.
Since the Vehicles class is just a container, mapping it as owned entity as you have tried seems the most natural way. However currently EF Core does not allow owned entity to be at the principal side of the relationship, and in your case this is needed.
So instead you need to map the Vehicles class as regular "entity" sharing the same table with the Customer - the so called table splitting. You have to do explcitly all that EF Core does implicitly for owned entities - define a shadow property and map is a both PK and FK for the one-to-one relationship with the Customer. You'd need also the explicitly map the Vehicle.CustomerId as a FK because from EF point of view the Vehicle is related to Vehicles rather than to Custome, hence the conventional FK property / column name assumed will be VehiclesId. Note that with this model you'll never be able to define an inverse navigation property Customer of the Vehicle.
With that being said, here is the fluent configuration needed:
modelBuilder.Entity<Vehicles>(builder =>
// Table
builder.ToTable(modelBuilder.Entity<Customer>().Metadata.Relational().TableName);
// PK
builder.Property<int>("Id");
builder.HasKey("Id");
// One-to-one relationship with Customer
builder.HasOne<Customer>()
.WithOne(e => e.Vehicles)
.HasForeignKey<Vehicles>("Id");
// One-to-many relationship with Vehicle
builder.HasMany(e => e.Items)
.WithOne()
.HasForeignKey(e => e.CustomerId);
);
and usage:
db.Customers
.Include(x => x.Vehicles.Items) // <--
// ...
edited Mar 24 at 10:18
answered Mar 24 at 10:06
Ivan StoevIvan Stoev
112k794149
112k794149
add a comment |
add a comment |
Use .Join
See this question for some examples:
Entity Framework Join 3 Tables
add a comment |
Use .Join
See this question for some examples:
Entity Framework Join 3 Tables
add a comment |
Use .Join
See this question for some examples:
Entity Framework Join 3 Tables
Use .Join
See this question for some examples:
Entity Framework Join 3 Tables
answered Mar 23 at 6:15
Ian PregloIan Preglo
30410
30410
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55311063%2fentity-framework-nested-joins%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
why do you have an entity vehicles as a container for a list of vehicles? That does not sound clean. If that's what you BO's look like, you should consider converting them into model objects to save one table and the one-to-one relationship. Also, you may consider either exposing or hiding all FK properties to be consistent.
– DevilSuichiro
Mar 23 at 9:26
This is unusual model, so it's not surprising that it's problematic to be mapped. The way
Vehiclesclass is defined in the example (w/o additional properties) it makes no sense. In order to try helping, we need to know the meaning ofVehiclesclass - is it an entity (and if yes, does it have its own table or has to be stored in theCustomertable) or just a some sort of a container class?– Ivan Stoev
Mar 23 at 13:44
It is a container class. It does not have its own table. The two tables involved in this are a customers table and a vehicles table. I'm attempting to reuse a large set of entities that exist in this solution. They aren't exactly representative of the database but are very close. I've been able to make the rest of it work with fluent mapping.
– Jacob
Mar 23 at 13:52