C#存储库和可本地化的实体

时间:2017-07-03 14:42:29

标签: c# dapper

在我的应用程序中,我有许多可本地化的实体。此实体的数据库结构 是here。某些表中的PK类型可能不同(其中一些是int,一些是bigint)。这取决于将在表中存储多少数据。 我使用Dapper作为ORM。

现在我有了这个解决方案(但内部的东西告诉我这个解决方案很糟糕):

// ENTITY
public abstract class Entity
{
    public object Id { get; set; }
}

public abstract class Entity<TKey> : Entity
{
    public new TKey Id { get; set; }
}

// LOCALIZABLE ENTITY
public abstract class LocalizableEntity<TTranslation> : Entity
    where TTranslation : EntityTranslation
{
    public ICollection<TTranslation> Translations { get; set; }
}

public abstract class LocalizableEntity<TKey, TTranslation> : Entity<TKey>
    where TTranslation : EntityTranslation
{
    public ICollection<TTranslation> Translations { get; set; }
}

// ENTITY TRANSLATION
public abstract class EntityTranslation
{
    public object LocalizableId { get; set; }

    public int LanguageId { get; set; }
}

public abstract class EntityTranslation<TKey> : EntityTranslation
{
    public new TKey LocalizableId { get; set; }
}

// REPOSITORIES

public class BaseRepository: IRepository, IDisposable
{
    public string ConnectionString { get; set; } 

    // ....
}

public abstract class BaseEntityRepository: BaseRepository
{
    protected IDbConnection Connection => _connection ?? (_connection = CreateDbConnection(GetConnectionStringValue(ConnectionString)));

    protected abstract IDbConnection CreateDbConnection(string connectionString);

    // SaveEntity<T>(T entity), DeleteEntity(object id)
}

public abstract class BaseEntityRepository<TEntity, TKey, TSearchOptions, TLoadOptions> : BaseEntityRepository
    where TEntity : Entity<TKey>
    where TSearchOptions : SearchOptions
    where TLoadOptions : LoadOptions
{
    // GetEntities(TSearchOptions sopts, TLoadOptions lopts), EntityCount(TSearchOptions) ...
}

public abstract class BaseLocalizableEntityRepository<TEntity, TKey, TEntityTranslation, TSearchOptions, TLoadOptions> : BaseEntityRepository<TEntity, TSearchOptions, TLoadOptions>
    where TEntity : Entity<TKey>
    where TEntityTranslation : EntityTranslation<TKey>
    where TSearchOptions : SearchOptions
    where TLoadOptions : LoadOptions
{
    // GetTranslations, SaveTranslation ...
}

好还是坏?如果不好,我该怎么做?

1 个答案:

答案 0 :(得分:0)

由于您需要高度可定制的本地化,因此您的解决方案并不是那么糟糕。如果我需要翻译,我的表现方式相同。但是,每个实体翻译具有不同的表格,我有一个唯一的表格,支持翻译的任何实体都参考:

CREATE TABLE Test_Translations
(
    Language char(10) NOT NULL,
    TextId int NOT NULL,
    Value text NOT NULL,
    CONSTRAINT Test_Translations_Language_TextId_pk PRIMARY KEY (Language, TextId)
);

CREATE TABLE Test_LocalizableStrings
(
    Id int NOT NULL CONSTRAINT Test2_Test1Id_pk primary key
);

ALTER TABLE Test_Translations ADD FOREIGN KEY (TextId) REFERENCES Test_LocalizableStrings;

Resulting Tables

然后在需要翻译支持的表中,只需为Test_LocalizableStrings创建一个引用键。在查询时查询TextIdLanguage