0

I have a Comment object with an optional user. On setting the user, I would like to set an additional field with the user's name so that if the user is later deleted the comment will be identifiable to humans.

public class Comment
{

    public int Id { get; set; }
    public int? CommenterId { get; set; }
    public string CommenterName { get; set; }
    public string Text { get; set; }
    public virtual UserProfile Commenter {  get; set; }
}

Commenter and CommenterId are mapped like so with FluentAPI:

HasOptional(t => t.Commenter)
    .WithMany()
    .HasForeignKey(t => t.CommenterId);

So I'd like to override the setter of Commenter and do something like this:

public virtual UserProfile Commenter{  get; set 
    {
        CommenterName = value.DisplayName;
        CommenterId = value.Id
    } 
}

When I set that up, I see that it is not valid to define a setter without defining a getter. I guess I could define the getter, which would mean looking up the user by Id, but that seems like I'd just be re-implementing something that already works. Is there a correct or better way to do this?

Julian Mann
  • 6,256
  • 5
  • 31
  • 43

1 Answers1

1

I guess I could define the getter, which would mean looking up the user by Id

Not exactly.

Your current implementation fails to ever set the user profile. You can implement the getter and the rest of the setter yourself (what you have now is an auto-property for the getter, and a manual implementation of the setter that doesn't set any backing value)

private UserProfile commenter;
public virtual UserProfile Commenter
{   
    get
    {
        return commenter;
    }
    set 
    {
        CommenterName = (value == null ? string.Empty : value.DisplayName);
        commenter = value;
    } 
}

Note if you're using C# 6 you can write the second to last line using the snazzy new Null Conditional operator.

CommenterName = value?.DisplayName;
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • I see - so an auto-property maintains that private field without me ever seeing it. Makes sense now. And thanks for the null conditional operator tip! – Julian Mann Feb 16 '16 at 00:17
  • Yes that's right... auto-property is syntactic sugar that creates the backing field for your property. – Eric J. Feb 16 '16 at 00:18