[英]Entity framework one to many relationship code first asp .net mvc 5 and jquery autocomplete
I want to create a simple website where user can add offerts with some details like title, description, city, time. 我想创建一个简单的网站,用户可以在其中添加一些详细信息,如标题,描述,城市,时间。
This is a part of my database diagram. 这是我的数据库图表的一部分。
City table 城市表
public class City
{
public int CityID { get; set; }
[StringLength(50, MinimumLength = 2)]
public string Name { get; set; }
public int RegionID { get; set; }
public virtual Region Region { get; set; }
public virtual ICollection<Offert> Offerts { get; set; }
}
Region table 区域表
public class Region
{
public int RegionID { get; set; }
[StringLength(30, MinimumLength=3)]
public string Name { get; set; }
public virtual ICollection<City> Cities { get; set; }
}
Offert table: 表格:
public class Offert
{
// Properties
public int OffertID { get; set; }
[Required]
[MaxLength(30)]
[Display(Name = "Title", ResourceType = typeof(Resource))]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Description", ResourceType = typeof(Resource))]
[StringLength(100, ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "Bad_Description", MinimumLength = 6)]
public string Description { get; set; }
[Required]
[DataType(DataType.DateTime)]
[Display(Name = "When", ResourceType = typeof(Resource))]
public DateTime When { get; set; }
// Relationships
public int CityID { get; set; }
[Display(Name = "City", ResourceType = typeof(Resource))]
public virtual City City { get; set;
public virtual ApplicationUser User { get; set; }
}
User table: 用户表:
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Offert> Offerts { get; set; }
public virtual MyUserInfo MyUserInfo { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
Relationships are are created using fluent api: 使用流畅的api创建关系:
public class Pako_Context : IdentityDbContext<ApplicationUser>
{
public Pako_Context()
: base("database_context")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
public static Pako_Context Create()
{
return new Pako_Context();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.HasMany(user => user.Offerts)
.WithRequired();
modelBuilder.Entity<Region>()
.HasMany(c => c.Cities)
.WithRequired(r => r.Region);
modelBuilder.Entity<City>()
.HasMany(o => o.Offerts)
.WithRequired(c => c.City);
}
public DbSet<City> Cities { get; set; }
public DbSet<Region> Regions { get; set; }
public DbSet<Offert> Offerts { get; set; }
public DbSet<MyUserInfo> MyUserInfo { get; set; }
}
I have 2 problems: 我有两个问题:
Offert create view: Offert创建视图:
<div class="form-group">
@Html.LabelFor(model => model.City.Name, "City", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City.Name, new { htmlAttributes = new { @class = "form-control", @id = "autocomplete", data_autocomplete_url = Url.Action("Autocomplete") } })
@Html.ValidationMessageFor(model => model.City.Name, "", new { @class = "text-danger" })
</div>
</div>
2. Currently as workaround of problem number 1, I just pick up some random city from database and add this to my offert. 2.目前作为问题1的解决方法,我只是从数据库中选择一个随机城市并将其添加到我的问题中。
Offert controller create method: Offert控制器创建方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OffertID,Title,Description,When,City.Name")] Offert offert)
{
if (ModelState.IsValid)
{
string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
offert.User = currentUser;
City RandomCity = db.Cities.FirstOrDefault();
offert.City = RandomCity;
db.Offerts.Add(offert);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(offert);
}
But when I invoke db.SaveChanges(); 但是当我调用db.SaveChanges()时; Method following exception occur: 发生异常的方法:
Additional information: Entities in 'Pako_Context.Offerts' participate in the 'ApplicationUser_Offerts' relationship. 附加信息:'Pako_Context.Offerts'中的实体参与'ApplicationUser_Offerts'关系。 0 related 'ApplicationUser_Offerts_Source' were found. 找到0个相关的'ApplicationUser_Offerts_Source'。 1 'ApplicationUser_Offerts_Source' is expected. 1'ApplicationUser_Offerts_Source'是预期的。
I tried to add offert record to ApplicationUser
but it didn't work. 我试图向ApplicationUser
添加offert记录,但它没有用。 Probably I don't understand this message correctly. 可能我没有正确理解这个消息。 How to resolve problems 1 and 2? 如何解决问题1和2?
For your first issue, you have to change the autocomplete and make it through JavaScript in order to pick the selected value from the user, then updae this value in a Hidden Field. 对于第一个问题,您必须更改自动完成并通过JavaScript进行操作以便从用户中选择所选值,然后在隐藏字段中更新此值。 You have to make this hidden field with the name CityID 您必须使用名称CityID创建此隐藏字段
@Html.HiddenFor(model => model.CityID)
If you are using Autocomplete plugin, then it should be like this: 如果您使用的是自动完成插件,那么它应该是这样的:
$("#City_Name").autocomplete({ source: "PUT the source here for your Cities", minLength: 2, select: function (event, ui) { $("#CityID").val(ui.item.id); } }) $(“#City_Name”)。autocomplete({source:“PUT the sources for your cities”,minLength:2,select:function(event,ui){$(“#CityID”)。val(ui.item。 ID); } })
As for the second issue, it says that you have a relation between User and Offers and this relation is required, so you have to have at least one offer in the Offers collection, so try to add this line: 至于第二个问题,它表示您在用户和要约之间存在关联,并且此关系是必需的,因此您必须在要约集合中至少有一个要约,因此请尝试添加以下行:
currentUser.Offerts.Add(offert);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.