我试图给我的外键列我想要的名字。
如果我使用builder.Property设置我的foreignKey,又名
var b = builder.Property(column.PropertyType, column.PropertyName);
b.ForSqlServerHasName("MyFKColumnName");
,当我创建关系时,我在迁移时出错: "导航属性' LettreClePrincipale'无法添加到实体类型' LettreCleAssociation'因为实体类型上已经存在同名的财产' LettreCleAssociation'。"
如果我没有使用builder.Property设置我的foreignKey,则此错误消失,密钥已正确创建,但我无法在此过程中设置名称:
ltcLinkBuilder.HasOne(typeof(LTC).FullName, "Link1")
.WithMany().IsRequired()
.HasForeignKey("Link1ID").OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Cascade)
.???
我已经定义了这样的模型(更多属性)
class LTC
{
public int TestA { get; set; }
public string TestB { get; set; }
public Guid Id { get; set; }
protected ICollection<LTCLinks> _links { get; set; }
public IReadOnlyList<LTCLinks> Links
{
get
{
return _links.ToList().AsReadOnly();
}
}
}
class LTCLinks
{
public Guid Link1ID { get; set; }
public LTC Link1 { get; set; }
public Guid? Link2ID { get; set; }
public LTC Link2 { get; set; }
public string Data { get; set; }
}
我这里没有ForSqlServerHasName或ForSqliteHasName扩展方法。我该如何着手实现这一目标?
在EFCore 1.1预览1上运行。
答案 0 :(得分:1)
LTC
和LTCLinks
之间有两种关系,我想EF不知道在LTC.Links
集合中使用哪一种...检查InverseProperty属性,你应该有类似的东西:
[InverseProperty("Link2")]
public IReadOnlyList<LTCLinks> Links {...}
关于您的原始问题,以下是有效的代码:
namespace ConsoleApp1
{
using Microsoft.EntityFrameworkCore;
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Bar
{
public int Id { get; set; }
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
}
public class MyDb : DbContext
{
public DbSet<Foo> Foos { get; }
public DbSet<Bar> Bars { get; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=test; Trusted_Connection=True");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>(t =>
{
t.HasKey(x => x.Id);
});
modelBuilder.Entity<Bar>(t =>
{
t.HasKey(x => x.Id);
t.Property(x => x.FooId).HasColumnName("FooIdColumn");
t.HasOne(x => x.Foo).WithMany().HasForeignKey(x => x.FooId).HasConstraintName("MyFK");
});
}
}
}
在project.json
:
"dependencies": {
"Microsoft.NETCore.App": { "type": "platform", "version": "1.0.1" },
"Microsoft.EntityFrameworkCore.Tools": { "type": "build", "version": "1.0.0-preview3-final" },
"Microsoft.EntityFrameworkCore.Design": { "type": "build", "version": "1.1.0-preview1-final" },
"Microsoft.EntityFrameworkCore.SqlServer": "1.1.0-preview1-final"
},
"tools": { "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final" },
"frameworks": {
"netcoreapp1.0": {}
}
生成并运行迁移后,我在SQL中: