.net EF Core将对象Map到多个数据库

vddsk6oq  于 2023-02-26  发布在  .NET
关注(0)|答案(2)|浏览(141)

我正在.NET Core中构建一个对象,该对象将使用EF CoreMap到数据库。但是,此对象的属性之一需要Map到单独的只读数据库。
我的意思是:

public class Sample
{
    public int Id { get; set; }
    [Required]
    public Location Location { get; set; }
    public string SampleValue { get; set; }
}

[Keyless]
public class Location
{
    [Column("LOCATION_ID")]
    public int Id { get; set; }
    [Column("LOCATION_DESC")]
    public string Name { get; set; }
}

Location对象是使用预定义的SQL查询从只读Oracle数据库中提取的,并使用FromSQL方法检索,这就是我使用[Keyless]属性的原因:

_dbContext.Locations.FromSql<Location>(query)

Sample将存储在SQL数据库中,位置将与Location ID一起存储在该数据库中,因此当我检索Sample对象时,EF Core将选取ID并从Oracle数据库中获取它,然后创建正确的Location属性并Map它

kgsdhlau

kgsdhlau1#

不幸的是,您将无法填充_dbContext.Locations.FromSql<Location>(query),因为您需要连接到不同的数据库。
DbContext不用于管理2个数据库的状态。如果您的域实体(示例)是从2个不同的数据源创建的,我建议不要依赖ORM框架,而是自己构建实体。

var dbSample = _dbContext1.DbSample.Get();
var dbLocation = _dbLocationContext.DbLocation.Get(dbSample.locationId);

return SampleBuilder.Build(dbSample, dbLocation);

这种方法的缺点是你必须实现从域实体到数据库表示的Map,但是这种方法更直接,也更容易实现和维护。

gz5pxeao

gz5pxeao2#

因此,按照@vshishkarov我决定做的事情:

public class Sample
{
    public int Id { get; set; }
    [Required]
    public string LocationId { get; set; }
    [NotMapped]
    public Location Location { get; set; }
    public string SampleValue { get; set; }
}

[Keyless]
public class Location
{
    [Column("LOCATION_ID")]
    public int Id { get; set; }
    [Column("LOCATION_DESC")]
    public string Name { get; set; }
}

var dbSample = _dbContext1.DbSample.Get();
var dbLocation = _dbLocationContext.DbLocation.Get(dbSample.locationId);

dbSample.Location = dbLocation;
return dbSample;

相关问题