简体   繁体   中英

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

I want the join to be on an id (real column) and comment type (string). The following example doesn't work but should indicate my intention.

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; }   
}

When this gets converted to sql I'd like it to translate to something like the following.

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

EDIT: Also by the way, when I try it this way I get the following error. "The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical."

I don't believe there's a way to do what you want AND make it a foreign key. There is no construct in SQL that allows a constant value to be part of a foreign key. You can use other constructs like a computed column, CHECK constraint or triggers to ensure that the underlying data data is "constant" but the foreign key has to reference table columns. These methods, however, cannot be configured using code first that I am aware of, so you'll have to configure those at the database level.

If you have to have a foreign key then I would suggest persisting the column in the database and making it a true foreign key, perhaps using business rules or one of the methods above.

A second option is to remove the foreign key attributes and just enforce the relationship (and the constant value) through business rules. (ie embed the constant value in your repository queries so that the equivalent SQL you specify is generated).

Something like

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}

or

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}

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.

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