Search code examples
asp.net-mvcentity-frameworkumbraco

EntityFramework and Umbraco - Use Umbraco Member NodeID as Foreign Key


I am currently creating some tables on a database for an Umbraco project (separate to the Umbraco DB).

I need one of the tables in the external DB to use the nodeId from the [dbo].[cmsMember] table in the Umbraco database.

Usually to add a foreign key I would add something to the model like:

public class Example {

    public int FKProperty { get; set; }

    [ForeignKey("FKProperty")]
    public FKEntity Entity { get; set; }

}

Is there a way to follow this same pattern with an Umbraco Member?

Thanks


Solution

  • Because you’re talking about using EF on a database that’s external to the Umbraco database, you won’t be able to take advantage of the ForeignKey attribute. What you can do instead is create a computed (NotMapped) property on your model and linking that to the Umbraco Member object, via the MemberId property that’s stored in your external database... something like this perhaps:

    public class Example {
    
        public int Key { get; set; }
    
        public int MemberId { get; set; }
    
        [NotMapped]
        public Member Entity {
            get 
            {
                return Umbraco.Core.ApplicationContext.Current.Services.Members.GetById(MemberId);
            }
            set
            {
                MemberId = value.Id;
            }
        }
    
    }
    

    You could also use Guid instead of int for your MemberId and call GetByKey instead of GetById

    You probably want to set the member to a private variable instead of retrieving it every time you need to reference the property.