实现通用的IEntityTypeConfiguration

时间:2019-01-16 10:40:05

标签: c# entity-framework-core

我正在尝试实现IEntityTypeConfiguration,我可以将其重新用于配置扩展实体:

<form class="form" method="POST" action="index.php" onsubmit="return checkval(event);">

  <input class="form-check-input" type="checkbox" value="" name="gdpr" id="gdpr_privacy">


  <input class="btn btn-primary btn-block" type="submit" name="submit" placeholder="Send" id="submit"></input>

</form>

获取错误:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public partial class Foo : IFoo
{
    public long Id { get; set; }
    public virtual Bar Bar { get; set; }
}

public interface IFoo
{
    long Id { get; set; }
    Bar Bar { get; set; }
}

public partial class Bar
{
    public long Id { get; set; }
    public long FooId { get; set; }
    public virtual IFoo Foo { get; set; }
}

public class FooConfig<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : class, IFoo
{
    public void Configure(EntityTypeBuilder<TEntity> builder)
    {
        builder.HasKey(e => e.Id);
        builder.HasOne(e => e.Bar)
            .WithOne(e => e.Foo);
    }
}

有什么方法可以“愚弄” lambda或构造FooConfig以便代码可以编译?从逻辑上讲,如果我使FooConfig为非通用的,我相信代码是正确的并且可以按预期进行编译和运行:

Error   CS0266  Cannot implicitly convert type 'IFoo' to 'TEntity'. An explicit conversion exists (are you missing a cast?)
Error   CS1662  Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

但是当我使用实际实体时,我无法覆盖Configure方法:

public class FooConfigNonGeneric : IEntityTypeConfiguration<IFoo>
{
    public void Configure(EntityTypeBuilder<IFoo> builder)
    {
        builder.HasKey(e => e.Id);
        builder.HasOne(e => e.Bar)
            .WithOne(e => e.Foo);
    }
}

错误:

public partial class FooExtended : Foo
{
    public string AnotherProperty { get; set; }
}

public class FooExtendedConfig: FooConfigNonGeneric
{
    public override void Configure(EntityTypeBuilder<FooExtended> builder)
    {
        base.Configure(builder);
    }
}

0 个答案:

没有答案