gpt4 book ai didi

c# - 具有 Active 标志的流畅映射和关系表

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:06 29 4
gpt4 key购买 nike

我有一个关系表,但有一个额外的列 Active bit not null

我不明白我应该如何在 EF6 中进行映射,我有 3 个表,FooBarFooBar,其中 FooBar 是关系表

FooBar {
FooId: int (Key and FK)
BarId: int (Key and FK)
Active: bit
}

Foo 实体

public class Foo
{
public int Id { get;set; }
public ICollection<FooBar> Bars { get; set; }
...
}

FooBar 实体

public class FooBar
{
public Foo Foo { get;set; }
public Bar Bar { get;set; }
public bool Active { get;set; }
}

现在到问题,EF 配置FooBar 配置

public class FooBarConfiguration : EntityTypeConfiguration<FooBar>
{
public FooBarConfiguration()
{
HasKey(fb => new[] {fb.Foo.Id, pv.Bar.Id}); //Is this correct?

Property(pv => pv.Active);

ToTable("ProductVehicle");
}
}

我不知道 Foo 配置应该是什么样的,所以我卡住了,尝试了类似的东西

public class FooConfiguration : EntityTypeConfiguration<Foo>
{
public FooConfiguration()
{
HasKey(f => f.Id);

HasMany(f => f.Bars)
.WithRequired(f => p.Foo)
.HasForeignKey(f => f.Foo.Id);

ToTable("Foo");
}
}

我明白了

A first chance exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: The properties expression 'f => f.Foo.Id' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

我也改变了 FooConfig

HasMany(f => p.Bars)
.WithRequired(fb => fb.Foo)
.Map(map => map.MapKey("FooId"));

我得到了一点时间,现在它在 FooBar 配置上失败了

A first chance exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: The properties expression 'fb => new [] {fb.Foo.Id, fb.Bar.Id}' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

编辑:我最终得到了这个解决方案,让它更受领域驱动,

public class ProductVehicle
{
private Product _product;
private Vehicle _vehicle;
internal int ProductId { get; set; }
internal int VehicleId { get; set; }

public Product Product
{
get { return _product; }
set
{
_product = value;
ProductId = value.Id;
}
}

public Vehicle Vehicle
{
get { return _vehicle; }
set
{
_vehicle = value;
VehicleId = value.Id;
}
}

public bool Active { get; set; }
}

最佳答案

你需要给 FooBar 添加一个属性,比如 FooId:

public class FooBar
{
...
public int FooId { get { return Foo.Id;}}
}

然后将代码更改为:

 HasMany(f => f.Bars)
.WithRequired(f => p.Foo)
.HasForeignKey(f => f.FooId);

关于c# - 具有 Active 标志的流畅映射和关系表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30570218/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com