我正在尝试使用Code First构建一个EF实体,并EntityTypeConfiguration使用流畅的API.使用Unique Constraint创建主键很容易,但不是这样.我看到旧帖子建议为此执行本机SQL命令,但这似乎打败了目的.这可能与EF6有关吗?
我有一个错误
Column 'key' in table 'misc_info' is of a type that is invalid for use as a key column in an index.
Run Code Online (Sandbox Code Playgroud)
其中key是nvarchar(max).一个快速谷歌发现了这一点.然而,它并没有解释什么是解决方案.我如何创建像Dictionary这样的键,其中键和值都是字符串,显然键必须是唯一的并且是单一的.我的sql语句是
create table [misc_info] (
[id] INTEGER PRIMARY KEY IDENTITY NOT NULL,
[key] nvarchar(max) UNIQUE NOT NULL,
[value] nvarchar(max) NOT NULL);
Run Code Online (Sandbox Code Playgroud) 我在Entity Framework 6.1.3中有以下数据模型:
using System.Data.Entity;
public class Student
{
public int Id { get; set; }
public virtual Contact Contact { get; set; }
}
public class Contact
{
public int Id { get; set; }
public virtual Student Student { get; set; }
}
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity<Contact>()
.HasOptional(x => x.Student)
.WithOptionalDependent(x => x.Contact)
.WillCascadeOnDelete(true);
}
}
public static class Program
{
private static void Main()
{
Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
using …Run Code Online (Sandbox Code Playgroud) 是否可以使用EF Fluent API将Discriminator列和另一个字符串列配置为唯一索引约束的一部分?
我有一个标识符列表,其中标识符可以是不同类型.每个标识符都有一个string类型的属性,用于保存标识字符串.
在我的情况下,客户可以使用不同的标识符.但每个鉴别器只能有一个带唯一字符串的标识符.
定义标识符类型的抽象类
public abstract class CustomerIdentifier : Entity<int>
{
public string Identifier { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
从CustomerIdentifier派生的具体类
class NationalIdNumberIdentifier : CustomerIdentifier
{
}
Run Code Online (Sandbox Code Playgroud)
我已经设法使用此处的答案为字符串列配置索引 ,实体框架中的多个列的唯一键约束如下所示
class CustomerIdentifierMap : EntityTypeConfiguration<CustomerIdentifier>
{
public CustomerIdentifierMap()
{
Property(p => p.Identifier).HasMaxLength(100).IsRequired().HasUniqueIndexAnnotation("UQ_IdentifierPerDiscriminator", 0);
}
}
Run Code Online (Sandbox Code Playgroud)
我需要以某种方式添加另一行,在此处指定discriminimnator应包含在唯一索引约束中.
我想知道在Entity Framework Core 2代码第一种方法中是否存在唯一约束的数据注释?
我试图首先使用fluent配置代码来强制执行列的唯一约束.有没有比在业务逻辑中实现它或使用类似下面的东西更好的方法
context.ObjectContext.ExecuteStoreCommand("CREATE UNIQUE CONSTRAINT...");
Run Code Online (Sandbox Code Playgroud)
或者我想知道是否不可能使用流畅的配置实现独特的约束?
编辑:
已经证实,使用流畅的配置是不可能的.但是我又想知道最好的方法是什么?并且想知道EF不支持这一点的原因.
public class A
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Aid { get; set; }
public virtual ICollection<B> B { get; set; }
}
public class B
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Bid { get; set; }
[Key]
[Column(Order = 0)]
[Required]
Public virtual string BName {get ; set}
[Key]
[Column(Order = 1)]
[Required]
public virtual int Aid { get; set; }
[ForeignKey("Aid")]
public virtual A A { get; set; }
public virtual ICollection<C> C { get; set; }
}
public class …Run Code Online (Sandbox Code Playgroud) c# entity-framework foreign-keys ef-code-first entity-framework-6