【问题标题】:Updating one of the related entity更新相关实体之一
【发布时间】:2016-10-26 12:47:35
【问题描述】:

我正在开发公告板系统(作为我培训 asp.net mvc 的一部分)。我对数据建模有基本的了解,但我对创建模型的方式有疑问。核心逻辑是发布具有以下类别的房地产、汽车和服务的广告。最初我尝试使用 TPH 方法,但随后遇到了绑定我的模型和自动映射器配置的问题。现在我想使用零或一个关系。

我有一个广告模型:

public class Ad
{
    public int ID { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public virtual Realty Realty { get; set; }

    public virtual Auto Auto { get; set; }

    public virtual Service Service { get; set; }
}

房地产:

public class Realty
{
    [Key]
    [ForeignKey("Ad")]
    public int AdID { get; set; }

    public string Type { get; set; }

    public string NumberOfRooms { get; set; }

    public virtual Ad Ad { get; set; }
}

Auto 和 service 模型与 Realty 模型具有相同的外键。

我的数据库上下文:

public DbSet<Ad> Ads { get; set; }
public DbSet<Realty> Realties { get; set; }
public DbSet<Auto> Autos { get; set; }
public DbSet<Service> Services { get; set; }

我只需要使用一种相关模型更新广告模型。我正在使用脚手架控制器操作,其中包括所有相关模型:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Title,Descirpiton,Realty,Auto,Service")] Ad ad)
{
    if (ModelState.IsValid)
    {
        db.Ads.Add(ad);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    ViewBag.ID = new SelectList(db.Autos, "AdID", "CarType", ad.ID);
    ViewBag.ID = new SelectList(db.Realties, "AdID", "Type", ad.ID);
    ViewBag.ID = new SelectList(db.Services, "AdID", "ServiceType", ad.ID);
    return View(ad);
}

问题在于,可以将广告与所有相关模型一起发布。在深入研究之前,我想确保我的做法是正确的。

谢谢。

【问题讨论】:

标签: asp.net-core-mvc entity-framework-core


【解决方案1】:

你已经接近了。根据您尝试执行的操作,您应该使用每个类型的表模型。您创建基础 (Ad),然后从它继承以创建子类型。

public class Ad
{
    [Key]
    public int ID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

[Table("Realty")]
public class Realty : Ad
{
    public string Type { get; set; }
    public string NumberOfRooms { get; set; }
}

您的上下文保持不变。当您知道正在创建哪种广告时,您现在可以创建适当的子类型。

var ad = new Realty();
ad.Title = "...";
ad.Description = "...";
ad.Type = "...";
ad.NumberOfRooms = "...";

您可以使用上下文中的特定类型来检索特定的广告类型。

db.Realty.ToList();

或者您可以检索所有广告并在遍历它们时询问类型。

var ads = db.Ads.ToList();

foreach(var ad in ads)
{
    if(ad is Realty)
        // do Realty stuff
    else if (ad is Auto)
        // do Auto stuff
}

【讨论】:

  • 谢谢克雷格,再问一个问题。我想为适当的子类型实现单个创建操作,这取决于视图中的用户选择。我应该向哪个方向寻求?谢谢。
  • 我不太明白你的问题。一旦你的实体类完全实现了,你可能应该发布一个比评论中更详细的新问题。
猜你喜欢
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多