SQLite:设计数据库并使用AUTOINCREMENT ID访问其数据的正确方法?

问题描述 投票:1回答:1

假设我有一个包含艺术家及其专辑的数据库。

CREATE TABLE Artist (
ArtistID INTEGER        PRIMARY KEY,
ArtistName TEXT NOT NULL
);


CREATE TABLE Album(
AlbumName TEXT PRIMARY KEY,
ArtistID INTEGER REFERENCES Artist(ArtistID),
Year INTEGER
);

那么我在Visual Studio中创建一个应用程序并使用sqlite / sql server紧凑工具箱将SQLite数据库连接到我的项目,然后我想用C#管理数据库

我为我的用户创建了一个应用程序。用户想要通过艺术家的名字找到所有专辑。

如果我的主键是自动增量属性,我是否必须使用如下语法:

public static IQueryable<Artist> GetPossibleArtists(string name)
{
    var matches = from match in dB.Artists where match.ArtistName == name select match;

    return matches;
}

public static Artist GetFirstArtistIfExists(string artistName)
{
    var artistMatches = GetPossibleArtists(artistName);

    if (artistMatches.Count() == 0)
        return null;
    return artistMatches.First();
}

所以我首先访问数据库以通过其ID找到艺术家,因为我不能简单地按艺术家的名字找到专辑,因为艺术家的名字不是主键,我不能通过艺术家的名字搜索“专辑”表名字,我只能通过艺术家的ID搜索这个表然后我终于可以通过艺术家的ID找到所有的专辑了

public static IQueryable<Album> GetPossibleAlbums(long artistID)
{
    var matches = from match in dB.Albums where 
                  match.ArtistID == artistID
                  select match;

    return matches;
}

问题是:1)我在这里做错了什么,是否有更好的方式访问艺术家的所有专辑,以便我不需要访问数据库“以其名称找到艺术家的ID”我设法找到artistID的所有专辑? 2)我可能错误地设计了我的数据库,有什么建议吗? 3)将艺术家的名字存储在“专辑”表格中是一个好主意,我如何才能保持艺术家的自动增量主键同时存在?

c# sqlite linq-to-sql
1个回答
1
投票

您需要JOIN才能将Albums表与ArtistID字段上的Artists表相关联

var matches = from a in dB.Albums join b in db.Artists on a.ArtistID equals b.ArtistID
              where b.ArtistName == artistName
              select a;

join clause C# reference

© www.soinside.com 2019 - 2024. All rights reserved.