Question: I am using Entity Framework 6.1.1 code-first.

I am trying to add a new property to my object (with migration and existing DB with values) that will be a unique

This is the object:

```
public class A
{
    public int ID { get; set; }
    public string Name { get; set; }
}

```

and after I edit:

```
public class A
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string NewUniqueValue { get; set; }
}

```

and the fluent api:

```
modelBuilder.Entity<A>().HasKey(x => x.Id);
modelBuilder.Entity<A>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

// after added new property
modelBuilder.Entity<A>().Property(x => x.NewUniqueValue).HasMaxLength(20).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = true }));

```

but when I try to run `Update-Database`, I get an error 

> 
> Duplicate key value is (null) 
> 
> 
> 

(obviously...)

So my question is: is there any way to call a function (from the code) to generate such a key?

To call this function for generation:

```
public static string Generate()
{
    Random rnd = new Random();

    var chars = "abcdef0123456789";
    var unique = String.Empty;

    for (int i = 0; i < 20; i++)
    {
        unique += chars[rnd.Next(0, chars.Length)];
    }

    return unique;
}

```

Answer: 
You should fill your empty `NewUniqueValue` cells at `Migration` section:

```
public override void Up()
{
    AddColumn("dbo.TableA", "NewUniqueValue", c => c.String(maxLength: 20));
    //you should add this row:
    Sql("UPDATE dbo.TableA SET NewUniqueValue = NEWID()")
    CreateIndex("dbo.TableA", "NewUniqueValue", unique: true);
}

public override void Down()
{
    DropIndex("dbo.TableA", "NewUniqueValue");
    DropColumn("dbo.TableA", "NewUniqueValue");
}

```
Duplicate error probably occur due to old record in database cannot accept null value, because NewUniqueValue column indexed.

for generate key in A class call Generate method:

```
public class A
{
    public A()
    {
        NewUniqueValue = Generate();
        //or use guid
        NewUniqueValue = Guid.NewGuid().ToString();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string NewUniqueValue { get; set; }

    public static string Generate()
    {
        Random rnd = new Random();

        var chars = "abcdef0123456789";
        var unique = String.Empty;

        for (int i = 0; i < 20; i++)
        {
            unique += chars[rnd.Next(0, chars.Length)];
        }

        return unique;
    }
}

```