EntityFramework与Umbraco:如何将Umbraco Member NodeID用作外键
Absolutely! You can absolutely use that familiar ForeignKey attribute pattern to connect your independent database table to Umbraco's [dbo].[cmsMember] table—here's a step-by-step breakdown to make it work seamlessly:
1. Build your custom entity model
Start by defining your custom entity with the foreign key pointing to the nodeId column of cmsMember (this is the primary key of the Umbraco member table):
public class Example { // Primary key for your custom table public int Id { get; set; } // Foreign key field mapping to cmsMember.nodeId public int MemberNodeId { get; set; } // Navigation property linked to the Umbraco member [ForeignKey("MemberNodeId")] public virtual CmsMember LinkedMember { get; set; } // Add your custom properties here public string CustomDataField { get; set; } }
2. Map the Umbraco cmsMember table to a model
Create a simple entity class to map Umbraco's existing cmsMember table—you only need to include the columns you plan to use (at minimum the nodeId primary key):
[Table("cmsMember")] public class CmsMember { [Key] public int nodeId { get; set; } // Optional: Include other cmsMember columns if you need them public string LoginName { get; set; } public string Email { get; set; } public DateTime CreateDate { get; set; } }
3. Configure your DbContext
Update your custom DbContext to include both entities, and optionally enforce relationship rules in the OnModelCreating method:
public class CustomDbContext : DbContext { public CustomDbContext(DbContextOptions<CustomDbContext> options) : base(options) { } public DbSet<Example> Examples { get; set; } public DbSet<CmsMember> CmsMembers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Configure the relationship explicitly (optional but recommended) modelBuilder.Entity<Example>() .HasOne(e => e.LinkedMember) .WithMany() // Umbraco's member has no knowledge of your custom entity, so omit the reverse navigation .HasForeignKey(e => e.MemberNodeId) .OnDelete(DeleteBehavior.Restrict); // Prevent accidental deletion of Umbraco members when deleting your custom records } }
Key considerations to keep in mind
- Referential integrity safety: Always use
DeleteBehavior.Restrict(orNoAction) instead of cascade deletes—you don't want deleting a record in your custom table to remove an Umbraco member. - Avoid modifying Umbraco's schema: Never alter the
cmsMembertable directly; keep your custom table fully independent to avoid breaking Umbraco updates. - Index for performance: Add an index on your
MemberNodeIdcolumn to speed up join queries between your custom table andcmsMember.
内容的提问来源于stack exchange,提问作者ib4nez

