Domanda

================ Problem ================

First of all, I'm using Entity framework (code first). I have the following class:

 public class RandomObject
 {
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), Column(Order = 1)]
    public int Id { get; protected set; }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), Column(Order = 2)]
    public Guid UniqueId { get; protected set; }

    public string Other { get; set; }
 }

I also have a migration-folder (package) where I seed the database with some objects.

    private void AddDefaultObjects(Context context)
    {
        var object1 = new RandomObject{ Other = "qsdf1" };
        var object2 = new RandomObject{ Other = "qsdf2" };
        var object3 = new RandomObject{ Other = "qsdf3" };

        var objects = new RandomObject[3]{object1 , object2 , object3 };

        context.RandomObjects.AddOrUpdate(object => object.Id, objects);
        context.SaveChanges();
    }

But when I add the objects, they all get the same UniqueId => NOK (but a different Id => OK)

================ Attempts ================

I tried adding the attribute

    [Index(IsUnique = true)]

or setting (in my migration-configuration file)

    column.DefaultValueSql = "newid()";

================ Result ================

Id   |   UniqueId
--------------------------------------------
19   |   db1e353e-7dd7-e311-8250-8c89a5c20da1
20   |   dc1e353e-7dd7-e311-8250-8c89a5c20da1
21   |   dd1e353e-7dd7-e311-8250-8c89a5c20da1
È stato utile?

Soluzione

Try this....I think your AddOrUpdate needs both parts of your composite primary key in the first argument:

context.RandomObjects.AddOrUpdate(object => 
                                  new { object.Id, object.UniqueId }, 
                                  objects);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top