我在stackoverflow.com上的第一個問題!祝我好運:)解釋在這個上下文中只支持原始類型或枚舉錯誤,同時在多個字段上使用AddOrUpdate匹配播種ASP.NET MVC
我試圖用種子一些測試數據的開發數據庫,需要兩個領域的匹配,並在這裏遇到解決How to seed data with AddOrUpdate with a complex key in EF 4.3
我得到Only primitive types or enumeration types are supported in this context.
錯誤as mentioned in the comments by lukyer問題。
但是,儘管按照他的建議添加了外鍵屬性和模型屬性的必需屬性,但我找不到明顯的方法來清除錯誤。
有關如何成功創建數據庫的任何想法都會非常感激。
模型的重要組成部分如下:
public class User {
public string ID { get; set; }
public string Email {get; set; }
}
public class Institution {
public Guid ID { get; set;}
public string Name {get; set; }
}
public class UserInstitutionAssociation {
public Guid ID { get; set; }
public virtual User User { get; set; }
public virtual Institution Institution {get; set;}
}
然後將代碼從configuration.cs遷移增加了一個用戶([email protected])和機構(絕密建立)。然後,它嘗試在用戶和企業之間添加關聯,只有在這兩者之間的關聯尚不存在的情況下,才應該添加關聯。
//Add User to Database
context.Users.AddOrUpdate(u => u.Email,
new User {
Email = "[email protected]"
});
context.SaveContext();
//Add Institution to Database
context.Institutions.AddOrUpdate(u => u.Name,
new Institution {
Name = "Top Secret Establishment"
});
context.SaveContext();
//Add Association between User and Institution
context.InstitutionUserAssociations.AddOrUpdate(u => new { u.User, u.Institution },
new InstitutionUserAssociation
{
User = context.Users.Single(x => x.Email=="[email protected]"),
Institution = context.Institutions.Single(x => x.Name=="Top Secret Establishment")
}
);
context.SaveContext();
我試圖改變在許多方面的模型,因爲我明白Lukyer已經建議,包括在這裏How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?
描述總之所有的解決方案,我曾嘗試沒有成功以下的所有組合:
public class UserInstitutionAssociation {
public Guid ID { get; set; }
[Required]
[ForeignKey("UserID")]
public virtual User User { get; set; }
[Required]
[ForeignKey("InstitutionID")]
public virtual Institution Institution {get; set;}
}
和
public class UserInstitutionAssociation {
public Guid ID { get; set; }
[Required]
[ForeignKey("User")]
public string UserID {get; set; }
public virtual User User { get; set; }
[Required]
[ForeignKey("Institution")]
public Guid InstitutionID { get; set; }
public virtual Institution Institution {get; set;}
}