繁体   English   中英

在实体框架中是否可以将常量字符串作为外键

[英]Is it possible in entity framework to have a constant string as a foreign key

我希望连接在 id(真实列)和注释类型(字符串)上。 以下示例不起作用,但应表明我的意图。

public class Something
{
    [Key]
    [Column(Order=1)]
    public long Id { get; set; }

    [Key]
    [Column(Order = 2)]
    // Does this have to be in the database?
    public string CommentType = "Something-type-comment";

    [ForeignKey("CommentRecordId,CommentType")]
    public Comment Comment { get; set; }
}

public class Comment
{
    [Key]
    [Column(Order=1)]
    public long CommentRecordId { get; set; }

    [Key]
    [Column(Order=2)]
    public string CommentType { get; set; }   
}

当它转换为 sql 时,我希望将其转换为如下所示的内容。

SELECT * from Something s 
    JOIN Comment c ON 
        s.Id = c.CommentRecordId 
            and
        c.CommentType = 'Something-type-comment'; --there is no corresponding field in Something table

编辑:顺便说一下,当我以这种方式尝试时,我收到以下错误。 “关系约束中的从属角色和主要角色中的属性数量必须相同。”

我不相信有一种方法可以做你想做的使它的外键。 SQL 中没有允许常量值成为外键一部分的构造。 您可以使用其他构造,如计算列、CHECK 约束或触发器来确保基础数据数据是“常量”,但外键必须引用表列。 但是,这些方法不能首先使用我知道的代码进行配置,因此您必须在数据库级别配置这些方法。

如果您必须有一个外键,那么我建议将该列保留在数据库中并使其成为真正的外键,可能使用业务规则或上述方法之一。

第二种选择是删除外键属性,并通过业务规则强制执行关系(和常量值)。 (即在您的存储库查询中嵌入常量值,以便生成您指定的等效 SQL)。

就像是

var query = from s in Something
            join c in Comment
            on new {s.Id, CommentType = "Something-type-comment"} equals 
               new {c.CommentRecordId, c.CommentType}
            select new {s, c}

或者

var query = from s in Something
            join c in Comment
            on s.Id equals c.CommentRecordId
            where c.CommentType == "Something-type-comment" 
            select new {s, c}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM