Column Name isn't changing / set as defined in the [Column(string name)] Attribute
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace Blockwoche.Models
{
public class IdeaViewModel
{
[Key]
[Display(Name = "ID")]
public long _Id { get; set; }
[Column("UserId")]
[ForeignKey(nameof(ApplicationUser.Id))]
public virtual ApplicationUser? User { get; set; }
[Required]
[StringLength(50)]
public required string Title { get; set; }
[Required]
[StringLength(255)]
public required string Description { get; set; }
/*[Required]
[StringLength(255)]
public required List<string> Category { get; set; }*/
[Required]
[Display(Name = "Posted At")]
[DataType(DataType.DateTime)]
public DateTime CreatedDate { get; set; }
[Required]
[DefaultValue(true)]
public bool isPublic { get; set; }
}
}
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace Blockwoche.Models
{
public class IdeaViewModel
{
[Key]
[Display(Name = "ID")]
public long _Id { get; set; }
[Column("UserId")]
[ForeignKey(nameof(ApplicationUser.Id))]
public virtual ApplicationUser? User { get; set; }
[Required]
[StringLength(50)]
public required string Title { get; set; }
[Required]
[StringLength(255)]
public required string Description { get; set; }
/*[Required]
[StringLength(255)]
public required List<string> Category { get; set; }*/
[Required]
[Display(Name = "Posted At")]
[DataType(DataType.DateTime)]
public DateTime CreatedDate { get; set; }
[Required]
[DefaultValue(true)]
public bool isPublic { get; set; }
}
}
3 Replies
try it with fluentAPI
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IdeaViewModel>()
.HasOne(i => i.User)
.WithMany()
.HasForeignKey("UserId")
.HasConstraintName("FK_IdeaViewModel_User");
base.OnModelCreating(modelBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IdeaViewModel>()
.HasOne(i => i.User)
.WithMany()
.HasForeignKey("UserId")
.HasConstraintName("FK_IdeaViewModel_User");
base.OnModelCreating(modelBuilder);
}
The Column is still Id :thinkHeadSideWaysCutePondering:

You need to explicitly define a foreign key property in addition to your navigation property
just noticed
[Column("UserId")]
public string UserId { get; set; } = null!; // this one
[ForeignKey(nameof(UserId))]
public virtual ApplicationUser? User { get; set; }
[Column("UserId")]
public string UserId { get; set; } = null!; // this one
[ForeignKey(nameof(UserId))]
public virtual ApplicationUser? User { get; set; }