I've created my model classes and the database context with the following command:
dotnet ef dbcontext scaffold "Server=localhost;Port=3306;Database=test;Uid=test;Pwd=1234;" MySql.Data.EntityFrameworkCore --output-dir src/Models
My MariaDB (version 10.1.8) database looks like this:
CREATE TABLE Lens(
LensID INT AUTO_INCREMENT,
LensManufacturer TEXT,
LensName TEXT,
LensIsSingleFocalLength BOOLEAN,
LensFocalLengthMin INT,
LensFocalLengthMax INT,
LensApertureMin TEXT,
LensApertureMax TEXT,
PRIMARY KEY (LensID)
);
CREATE TABLE Camera(
CameraID INT AUTO_INCREMENT,
CameraManufacturer TEXT,
CameraModel TEXT,
PRIMARY KEY(CameraID)
);
CREATE TABLE Author(
AuthorID INT AUTO_INCREMENT,
AuthorAlias TEXT,
AuthorFirstName TEXT,
AuthorLastName TEXT,
PRIMARY KEY (AuthorID)
);
CREATE TABLE Image(
ImageID INT AUTO_INCREMENT,
LensID INT,
CameraID INT,
AuthorID INT,
ImagePath VARCHAR(255),
ImageTitle TEXT,
ImageDescription TEXT,
ImageTakenOn DATE,
ImageShutterSpeed TEXT,
ImageAperture DECIMAL(5,1),
ImageISO INT,
PRIMARY KEY (ImageID),
FOREIGN KEY (LensID) REFERENCES Lens(LensID),
FOREIGN KEY (CameraID) REFERENCES Camera(CameraID),
FOREIGN KEY (AuthorID) REFERENCES Author(AuthorID)
);
When I'm using the database context to get an Image I only get the data that is inside the Image table and the Objects representing the lens, the camera and the author are null.
How can I join the tables using Microsoft.EntityFrameworkCore?
Or should I use a view that joins the tables for me?
Try using LINQ to get the values of foreign keys:
var all = (
from i in ctx.Image
join c in ctx.Camera on i.CameraId equals c.CameraId
select new { i, c }
).ToArray();
You can use LINQ query for joining multiple tables in Entity Framework. like below
var Reg = (from app in db.Images
join Aut in db.Authors on app.AuthorID equals Aut.AuthorID
join Cam in db.Cameras on app.CameraID equals Cam.CameraID
join L in db.Lens on app.LensID equals L.LensID
select new ImageVM
{
ImageTitle = app.ImageTitle,
AuthorFirstName = Aut.AuthorFirstName,
CameraManufacturer = Cam.CameraManufacturer,
LensName = L.LensName
}).ToList();
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.