I'm using Entity Framework 6.1 code-first and my domain model is below.
class Item { [Index] public string CreatedBy { set; get; } }
When I use update-database for migration, I get the following error. However as far as I researched [Index]
should work as annotation to string
.
Column 'CreatedBy' in table 'dbo.Items' is of a type that is invalid for use as a key column in an index.
The Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. Because a string is a sequence, it can be accessed in the same ways that other sequence-based data types are, through indexing and slicing.
Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys. In order to use composite keys, Entity Framework requires you to define an order for the key properties. You can do this by using the Column annotation to specify an order.
EF Core only supports one index per distinct set of properties. If you configure an index on a set of properties that already has an index defined, either by convention or previous configuration, then you will be changing the definition of that index.
Usually you get this error when you use a VARCHAR(Max) try using:
[Column(TypeName = "VARCHAR")] [StringLength(n)] [Index] public string CreatedBy { set; get; }
where n is between 1 and 450.
If you use EntityTypeConfiguration aka mappings :
public class MyPocoEntitiyTypeConfig<T> : EntityTypeConfiguration<T> where T:class { } public class MyPocoEnt { public virtual string MyProp { get; set; } } public class MyPocoEntMapping : MyPocoEntitiyTypeConfig<MyPocoEnt> { public MyPocoEntMapping() { Property(x => x.MyProp).HasMaxLength(300); Property(x => x.MyProp).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("MyProp") { IsUnique = true })); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With