【问题标题】:How should I create this relationship in Entity Framework?我应该如何在实体框架中创建这种关系?
【发布时间】:2019-08-11 20:37:25
【问题描述】:

在我之前的问题中,我提到我正在开发一个销售点应用程序。我使用的平台是 WPF、MVVM 和实体框架(代码优先)。由于实体框架代码优先有自己的逻辑来映射实体和关系,我对一个案例感到困惑。

我有一个EntityBase 类:

public class EntityBase
{
    public DateTime? CreatedAt { get; set; }
    public User CreatedBy { get; set; }
    public DateTime? UpdatedAt { get; set; }
    public User UpdatedBy { get; set; }
}

public class User : EntityBase
{
    public int UserId { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

既然User类有EntityBase类成员,会不会在数据库端出现问题?

或者我应该像这样保留数据:

public class EntityBase
{
    public DateTime? CreatedAt { get; set; }
    public int CreatedByUserId { get; set; }
    public DateTime? UpdatedAt { get; set; }
    public int UpdatedByUserId { get; set; }
}

【问题讨论】:

    标签: c# sql-server entity-framework orm


    【解决方案1】:

    以这种方式创建您的模型:

    public class EntityBase
        {
            public DateTime? CreatedAt { get; set; }
            public int CreatedById { get; set; }
            [ForeignKey("CreatedById")]
            public User CreatedBy { get; set; }
            public DateTime? UpdatedAt { get; set; }
            public int UpdatedById { get; set; }
            [ForeignKey("UpdatedById")]
            public User UpdatedBy { get; set; }
        }
    
        public class User
        {
            public int UserId { get; set; }
            public string Username { get; set; }
            public string Password { get; set; }
        }
    

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多