我已经使用以下命令创建了模型类和数据库上下文:
dotnet ef dbcontext scaffold "Server=localhost;Port=3306;Database=test;Uid=test;Pwd=1234;" MySql.Data.EntityFrameworkCore --output-dir src/Models
我的MariaDB(版本10.1.8)数据库如下:
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)
);
当我使用数据库上下文获取图像时,我仅获取图像表中的数据以及代表镜头,相机和作者的对象。
如何使用Microsoft.EntityFrameworkCore加入表?
还是我应该使用一个为我联接表的视图?
答案 0 :(得分:1)
尝试使用LINQ来获取外键的值:
bin
答案 1 :(得分:1)
您可以使用LINQ查询在Entity Framework中联接多个表。像下面一样
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();