Reputation: 25
I'm having a problem with Entity Framework 5 and MVC C# 4.
I have a model (medical) 'Measurement' with the following properties:
[DataMember]
public int ID { get; set; }
[Required]
[DataMember(IsRequired = true)]
[Column(TypeName = "DateTime2")]
public DateTime Date { get; set; }
[Required]
[DataMember(IsRequired = true)]
public Status Status { get; set; }
[Required]
[DataMember(IsRequired = true)]
public User User { get; set; }
[Required]
[DataMember(IsRequired = true)]
public virtual List<Result> Results { get; set; }
The model Result is like this:
[DataMember]
public int ID { get; set; }
[DataMember]
public int Revision { get; set; }
[DataMember]
public string Comment { get; set; }
[DataMember]
public string ValueString { get; set; }
[DataMember]
public int ValueInt { get; set; }
[Required]
[DataMember]
public virtual MeasurementType MeasurementType { get; set; }
And the model MeasurementType (like Length, Age, Sex, Bloodpressure) is:
public int ID { get; set; }
[Required]
[DataMember]
public string Name { get; set; }
[DataMember]
public string Unit { get; set; }
I've got a Repository for the connection with the DbContext. When I want to add a new Measurement, the MeasurementType, User, Company and Roles (both in User) are also added into the database, but they are already present in the DB. Result is that there are a lot of duplicates of MeasurementType and Users
This is the method for adding a new measurement:
public void Post(Measurement measurement)
{
db.Measurements.Add(measurement);
db.SaveChanges();
}
I know the problem, the EntityState of Measurement.User and Result.MeasurementType has to be Unchanged in stead of Added, but I can't get them on Unchanged. I've tried several solutions found here on SO like Attach(Measurement.MeasurementType) but that give me an error like "An object with the same key is already in the ObjectStateManager".
What have I done wrong? Is it the model or the relationships between Measurement and MeasurementType (many-to-many) or is the error in the Repository-method or is the use of the keyword 'Virtual' not the best method?
Upvotes: 2
Views: 1208
Reputation: 3392
You have to create your foreign keys explicitly, for example:
public int UserId { get; set; }
public virtual User User { get; set; }
Then you can do:
User u = GetUserById(1);
myMeasurement.UserId = u.Id;
Upvotes: 2