Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating string index with Code first

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.

like image 341
DarthVader Avatar asked Dec 29 '14 10:12

DarthVader


People also ask

Can you index a string in Python?

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.

How do I set primary key in Entity Framework?

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.

Does EF core have index?

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.


2 Answers

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.

like image 100
Talal Yousif Avatar answered Oct 14 '22 07:10

Talal Yousif


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 }));         }     } } 
like image 29
Ognyan Dimitrov Avatar answered Oct 14 '22 08:10

Ognyan Dimitrov