简体   繁体   English

实体框架一对多关系代码首先是asp .net mvc 5和jquery autocomplete

[英]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. 这是我的数据库图表的一部分。

在此输入图像描述

  1. User can create many offerts 用户可以创建许多错误
  2. City can have many offerts 城市可能会有很多问题
  3. Region can have many cities. 地区可以有很多城市。

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: 我有两个问题:

  1. How to pass data from view to controller? 如何将数据从视图传递到控制器? Currently jquery autocomplete mechanism returns string which contains city name, but this value is not visible inside controller. 目前jquery自动完成机制返回包含城市名称的字符串,但此值在控制器内部不可见。

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.

相关问题 ASP.net MVC实体框架更新多对多关系 - ASP.net MVC Entity framework update Many to Many relationship ASP.NET MVC-实体框架多对多关系,插入数据 - Asp .NET MVC - Entity Framework many to many relationship, insert data ASP.NET MVC 5和实体框架多对多关系 - ASP.NET MVC 5 & Entity Framework many to many relationship ASP.NET MVC3和实体框架 - 一个视图中的一对多关系 - ASP.NET MVC3 and Entity Framework- one-to-many relationship in one view Entity Framework 5.0代码首先是一对一和一对多的关系 - Entity Framework 5.0 code first one to one and one to many relationship 使用实体框架的代码优先方法在ASP.NET MVC应用程序中缺少外键关系 - Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework 首先在ASP.net MVC实体框架代码中创建外键关系 - Create Foreign Key Relationship in ASP.net MVC Entity Framework Code First 实体框架-代码优先-共享主键一对多关系 - Entity Framework - Code first - One to Many relationship with shared primary key 无需代码优先模型创建的一对多关系实体框架 - One To Many relationship entity framework without Code First Model Creation Code First Entity Framework不会创建一对多关系 - Code First Entity Framework doesn't create one to many relationship
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM