开发者

With EF CodeFirst, how can I specify the ID when creating an object?

I have the following objects:

public class User {
    int Id { get; set; }
    string Name { get; set; }
    IList<Job> Jobs { get; set; }
}

public class Job {
    int Id { get; set; }
    DateTime StartTime { get; set; }   // other fluff values here
    User User { get; set; }
}

I've already set up a many-to-many relationship between User and Job (as it's appropriate), but I'd like to specify Job.Id when creating them. I can guarantee, although perhaps Entity can't, that the Ids are unique since they're the PK of another table in a different system.

The following code illustrates what I want to work:

var user = db.Users.Create ();
var job = new Job();
job.Id = 42; // id from other service
user.Jobs.Add (job);

db.Users.Add (user);
db.Save ();

Some code is being omitted for brevity, and please let me know if I've omit开发者_JS百科ted something that turns out to be necessary. My User gets created and inserted, my Job gets created and inserted, but Job.Id is 1 instead of 42.

What am I missing?


public class Job {
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    int Id { get; set; }
    DateTime StartTime { get; set; }   // other fluff values here
    User User { get; set; }
}

Should do what you need.

From DataAnotations

Setting the DatabaseGeneratedAttribute on a column to Identity or Computed forces the value for the column to be retrieved from the server as an Identity or Computed value when you call SaveChanges. Identity properties are read from the data source when the type is first saved, but afterward, they are assumed to be unchanged. Computed properties are read every time SaveChanges is called. None indicates that it is not a server generated property. Identity is the default value for integer key properties when working with Code First.

DatabaseGenerated reference

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜