DBContext metadata errors containing unique objects with foreign keys reset

Most messages around the ObjectStateManager are true duplicate issues based on unique primary keys. My problem is that my table does not have a primary key, but has several foreign keys, one of which is Nullable.

class MyObject
{
    int   Key1;
    int?  Key2;
}


context.MyTable.Attach(new MyObject() { Key1 = 100; Key2 = null; });
context.MyTable.Attach(new MyObject() { Key1 = 100; Key2 = 2000; }); ****

It will explode in the second call, although this is a unique row in the database.

Any thoughts on how to get around this? or forcibly check for two BOTH keys?

+4
source share
1 answer

@BenAaronson, . Entity Framework , , β€” , , /. , EF , . :

public class MyClass 
{
    public int MyClassId { get; set; }
    public int MyOtherClassId { get; set; }
}

, , EF , MyClassId MyClass, .

EF , , (, , ).

, , , EF - ( , Key1). :

context.MyTable.Attach(new MyObject() { Key1 = 100; Key2 = null; });

MyObject, 100 Key2 null.

:

context.MyTable.Attach(new MyObject() { Key1 = 100; Key2 = 2000; });

, 100, . , , , 100 ( ).

Key2 null , , . @BenAaronson :

public class Object
{
    // Alternatively, you can use a mapping class to define the primary key
    // I just wanted to make the example clear that this is the
    // surrogate primary key property.
    [Key]
    private int ObjectID { get; set; } // IIRC, you can make this private...
    public int Key1 { get; set; }
    public int Key2 { get; set; }
}

:

context.MyTable.Add(new MyObject() { Key1 = 100, Key2 = null; });
context.MyTable.Add(new MyObject() { Key1 = 100, Key2 = 2000; });

. Add, Attach. , Attach , , , ; , , context.SaveChanges(). Attach Unmodified. , . , . Add. Added. , . , Added, context.SaveChanges(), , Unmodified.

. " ", EF ( , . ). , --. " ". , , .

, : (.. ) ( , , ), . EF . , , ( , ), . :

public class A
{
    public int ID { get; set; }
}

public class B
{
    public int ID { get; set; }
}

public class AToB
{
    // Composite primary key
    [Key]
    public int IdA { get; set; }
    [Key]
    public int IdB { get; set; }

    public A SideA { get; set; }
    public B SideB { get; set; }

    // An additional property in the many-to-many join table
    public DateTime Created {  get; set; }
}

, EF . :

myA.AToB.SideB  // Accesses the related B item to this A item.
myA.AToB.Created // Accesses the created property of AToB, telling you
                 // when the relationship between A and B was created.

, , , EF .

Entity Framework.

0

Source: https://habr.com/ru/post/1534487/


All Articles