扩展EF Core模型的构建器设计模式

我有三个持久性类(EF Core),我想为Bot创建一个builder design pattern表示形式,因为它更舒适。

public class CryptoPair
{
    public int Id { get; set; }
    public string Symbol { get; set; }
    public string Description { get; set; }

    public List<Bot> Bots { get; set; }
}

public class TimeInterval
{
    public int Id { get; set; }
    public KlineInterval Interval { get; set; }
    public string Description { get; set; }

    public List<Bot> Bots { get; set; }
}

public class Bot
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Status { get; set; }

    public int UserId { get; set; }
    public User User { get; set; }

    public int CryptoPairId { get; set; }
    public CryptoPair CryptoPair { get; set; }

    public int TimeIntervalId { get; set; }
    public TimeInterval TimeInterval { get; set; }
}

下面的代码将以以下方式工作:

Bot bot = new BotBuilder()
    .Name("Bot Name")
    // Status should be false by default
    .UserId(1)
    .CryptoPairId(1)
    .TimeIntervalId(1)
    .Build();
public class BotBuilder
{
    private readonly Bot _bot;

    public BotBuilder()
    {
        _bot = new Bot();
    }

    public BotBuilder Name(string name)
    {
        _bot.Name = name;
        return this;
    }

    public BotBuilder Status(bool status)
    {
        _bot.Status = status;
        return this;
    }

    public BotBuilder UserId(int userId)
    {
        _bot.UserId = userId;
        return this;
    }

    public BotBuilder CryptoPairId(int cryptoPairId)
    {
        _bot.CryptoPairId = cryptoPairId;
        return this;
    }

    public BotBuilder TimeInterval(int timeIntervalId)
    {
        _bot.TimeIntervalId = timeIntervalId;
        return this;
    }

    public Bot Build()
    {
        return _bot;
    }
}

我想拥有两种建造者。

第一个应该使用EF Core在dbContext中添加新的加密对和时间间隔:

Bot bot = new BotBuilder()
    .Name("Bot Name")
    // Status should be false by default
    .UserId(1)
    .CryptoPair
        .Symbol("etc")
        .Description("smt")
    .TimeInterval
        .Interval(5)
        .Description("asd")
    .Build();

当然还要检查CryptoPair / TimeInterval是否为null,因为由于这种关系无论如何都会抛出异常。

第二个:

Bot bot = new BotBuilder()
    .Name("Bot Name")
    // Status should be false by default
    .UserId(1)
    .CryptoPair
        .WithExistingId(1)
    .TimeInterval
        .WithExistingId(5)
    .Build();

第二个很容易说明。

chendodo2009 回答:扩展EF Core模型的构建器设计模式

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3004532.html

大家都在问