使用自定义表和字段名称时如何在EF Core中为关系建模

时间:2018-12-10 22:59:06

标签: c# entity-framework

我正在尝试使用EF Core为现有MsSQL Db中的两个表之间的关系建模,但是Db的表使用自定义表名和列名。

即使我使用属性或FluentAPI指定关系,EF Core也无法建立关系。

我认为问题在于,因为我具有表和列的非常规名称,并且EF无法正确建立关系。

这是SQL:

CREATE TABLE paid_authors
(
    paid_author_id varchar(50) NOT NULL,
    [name] varchar(50) NOT NULL
)

CREATE TABLE hardback_books
(
    hardback_book_id uniqueidentifier NOT NULL,
    paid_author_id varchar(50) NOT NULL,
    title varchar(50) NOT NULL
)

INSERT INTO paid_authors VALUES ('duck' ,'Scrooge McDuck')
INSERT INTO hardback_books VALUES (NEWID(), 'duck', 'Duck Tales')

这是C#建模:

[Table("paid_authors")]
public class PaidAuthor
{        
    [Key]
    [Column("paid_author_id")]
    public string PaidAuthorId { get; set; }

    [Column("name")]
    public string Name { get; set; }

    public virtual List<HardbackBook> HardbackBooks { get; set; }
}

[Table("hardback_books")]
public class HardbackBook
{
    [Key]
    [Column("hardback_book_id")]
    public Guid HardbackBookId { get; set; }

    [Column("title")]
    public string Title { get; set; }

    [ForeignKey("HardbackBooks")] // This could be wrong!
    [Column("paid_author_id")]
    public string PaidAuthorId {get; set;}
}

我的代码:

foreach(var author in context.PaidAuthors.Take(10))
{
    // This next line makes it work, but it shouldn’t be needed!
    // author.HardbackBooks = context.HardbackBooks.Where(x => x.PaidAuthorId == author.PaidAuthorId).ToList();

    Console.WriteLine(author.PaidAuthorId + " - " + author.Name);
    Console.WriteLine(author.HardbackBooks.Count);
}

运行代码时,我得到System.NullReferenceException并且author.HardbackBooks为空。

我尝试了FluentAPI,并在父类上指定了ForeignKey ...但是肯定有一些我所缺少的东西!如果可以在其中运行,我很高兴切换到FluentAPI。

不用说,我无法更改Db结构...:-(

1 个答案:

答案 0 :(得分:0)

您不能将集合“导航属性”保留为空,并且在书上应该具有反向导航属性。像这样:

[Table("paid_authors")]
public class PaidAuthor
{
    [Key]
    [Column("paid_author_id")]
    public string PaidAuthorId { get; set; }

    [Column("name")]
    public string Name { get; set; }

    public virtual List<HardbackBook> HardbackBooks { get; } = new HashSet<HardbackBook>();
}

[Table("hardback_books")]
public class HardbackBook
{
    [Key]
    [Column("hardback_book_id")]
    public Guid HardbackBookId { get; set; }

    [Column("title")]
    public string Title { get; set; }

    public PaidAuthor PaidAuthor { get; set; }

    [ForeignKey("PaidAuthor")] 
    [Column("paid_author_id")]
    public string PaidAuthorId { get; set; }
}