michasaucer
michasaucer

Reputation: 5228

EntityFramework, getting Object ID while added to table

I have a question. Im adding object to my table in this way:

this.db.Objects.Add(new Object { Text = "someText", Number = number });

Then, i want to add second object to another table that is related to Objects table (table name is Objects3)

this.db.Objects3.Add(new Object3 { ObjectId = ?, Property = "text" });

How to get Object.Id (Id in tabel is int type) based only on Object's propertys?

Table looks like this:

public class Object
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Object2")]
    public int Object2Id { get; set; }
    public Object2 Object2 { get; set; }

    public string Text { get; set; }
    public int Number { get; set; }

    public List<Object3> Objects3 { get; set; }
}

public class Object3
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Object")]
    public int ObjectId { get; set; }
    public Object Object { get; set; }

    public string Property { get; set; }
}

Upvotes: 1

Views: 1208

Answers (1)

Wiktor Zychla
Wiktor Zychla

Reputation: 48240

You don't really need values of IDs to create a relation between two entities, this is where the ORM's support for navigation properties becomes handy:

var o1 = new Object() { ...
var o3 = new Object3() { ...

o3.Object = o1;

this.db.Objects3.Add( o3 );

this.db.SaveChanges();

EF should notice your navigation property has an object at the other end and save both to the database, in proper order, and set both IDs accordingly.

However, if you insist on having the ID in an explicit way, you should first save changes so that the ID is set in the object

var o1 = new Object() { ...
this.db.Objects.Add( o1 );

this.db.SaveChanges(); 

var id = o1.ID;

Now you can use your ID in an explicit way.

A side note - your navigation properties lack virtual modifier, this will make it impossible for the EF to replace the default implementation with the lazy-loading one for objects that are materialized when queries are executed against the database.

public class Object
{
    public Object()
    {
        this.Objects3 = new List<Object3>();
    }

    public virtual ICollection<Object3> Objects3 { get; set; }
}

public class Object3
{
    public virtual Object Object { get; set; }

}

Upvotes: 2

Related Questions