将ID转换为字符串类型

时间:2019-10-28 22:52:41

标签: c# entity-framework .net-core

模型表示一个带有ID的简单对象。 Id映射到也是数字类型的DB列。但是要求是将数字和字符串格式的ID都传递给客户端。这是必需的,因为Id是bigInt,并且某些客户端应用程序不支持bigInt类型,因此应将字符串变体传递给客户端。

但是,该字符串ID在数据库中不存在。因此,这是必须即时生成的。有没有办法在onModelCreating的映射中实现此目的?

我尝试使用Hasconversion(),但到目前为止还没有运气。

 public class Model
 {
   public long ModelId { get; set; }
   public string ModelIdString { get; set; }
   public decimal ModelValue { get; set; }
 }
public class ModelContext : DbContext
{
     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         base.OnModelCreating(modelBuilder);

         //configure column names
         modelBuilder.Entity<Model>().ToTable("db_model", "user_dba");


         modelBuilder.Entity<Model>(p =>
         {
             p.Property(md => md.ModelId).HasColumnName("model_id");
             p.Property(md => md.ModelIdString).HasColumnName("model_id").HasConversion<string>();
             p.Property(md => md.ModelValue).HasColumnName("value");
          });
     }
}

2 个答案:

答案 0 :(得分:1)

我不建议仅由于客户端应用程序要求而对模型进行更改。
而是创建表示客户端应用程序所需的数据结构的专用类,并将数据库模型映射到客户端数据结构。

这会将数据库模型与客户端需求隔离开来,使您可以自由设计数据库而无需依赖客户端需求。此外,它将保护您的模型不受客户端将来可能发生的更改的影响。
例如,您可以仅公开客户端应该看到的字段,而隐藏对您自己的应用程序至关重要的字段。

public class Model
{
    public int Id { get; set; }
    public string Value { get; set; }
    public string SecretKey { get; set; } // "hidden" from the client
}

public class ClientModel
{
    public string Id { get; set; }
    public string Value { get; set; }
}

从数据库中检索模型时,将其映射到客户端模型

var clientModel = dbContext.Models
    .Where(model => model.Id = someId)
    .Select(model => new ClientModel
    {
        Id = model.Id.ToString(),
        Value = model.Value
    })
    .ToList();

或者您可以为模型创建扩展方法

public static ClientModel ToClientModel(this Model model)
{
    return new ClientModel
    {
        Id = model.Id.ToString(),
        Value = model.Value
    };
}

var clientModel = dbContext.Models
    .Where(model => model.Id = someId)
    .Select(model => model.ToClientModel())
    .ToList();

答案 1 :(得分:0)

由于数据库中不存在字符串ID,因此可以从映射中排除ModelIdString属性。

 app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = "swagger";
                c.OAuthClientId(swaggerUIOptions.ClientId);
                c.OAuthClientSecret(swaggerUIOptions.ClientSecret);
                c.OAuthRealm(azureActiveDirectoryOptions.ClientId);
                c.OAuthAppName("Swagger");
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });