ASP.NET MVC使用代码优先,一对多CRUD
本文关键字:一对多 CRUD 代码 NET MVC ASP | 更新日期: 2023-09-27 18:20:55
我正在开发ASP.NET MVC Web应用程序。我使用的是代码优先的方法。我的模型类是:
public class Post
{
public int PostId { get; set; }
public PostType PostType { get; set; }
public DateTime DateTimeSubmitted { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string CSS { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
}
和
public class Asset
{
public int AssetID { get; set; }
public int PostId { get; set; }
public AssetType AssetType { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Text { get; set; }
public string Path { get; set; }
public string EmbeddedCode { get; set; }
public DateTime DateTimeSubmitted { get; set; }
public string ImageMineType { get; set; }
public Byte[] AssetData { get; set; }
public string CSS { get; set; }
public virtual Post Post { get; set; }
}
我遇到的问题是,当我试图创建Asset
时,只有Asset
。当我试图实现这一点时,也会创建Post
。当我尝试将新的Asset
添加到现有的Post
时,也会发生同样的情况。
这很好(用Asset
创建Post
):
[HttpPost]
public ActionResult AddPost(InspiredByModel data, HttpPostedFileBase image)
{
Post post = new Post();
Asset asset = new Asset();
if (image != null)
{
asset.ImageMineType = image.ContentType;
asset.AssetData = new byte[image.ContentLength];
image.InputStream.Read(asset.AssetData, 0, image.ContentLength);
}
post.Name = data.Name;
post.Description = data.Description;
asset.DateTimeSubmitted = DateTime.Now;
post.DateTimeSubmitted = DateTime.Now;
post.Assets = new List<Asset>();
post.Assets.Add(asset);
db.Posts.Add(post);
db.SaveChanges();
return View("Index");
}
这不起作用(新的Post
也被创建,Asset.postId
被分配给新装箱的Post
):(注:PostId
是硬编码的,用于测试目的)
[HttpPost]
public ActionResult AssetUploader(Asset asset, HttpPostedFileBase image)
{
if (image != null)
{
asset.ImageMineType = image.ContentType;
asset.AssetData = new byte[image.ContentLength];
image.InputStream.Read(asset.AssetData, 0, image.ContentLength);
}
var post = db.Posts.Where(p => p.PostId == 1).FirstOrDefault();
asset.DateTimeSubmitted = DateTime.Now;
post.Assets.Add(asset);
db.Entry(post).State = EntityState.Modified;
db.SaveChanges();
return View();
}
我正在为我的问题寻求帮助/解释/解决方案:
- 使用实体框架和Linq管理一对多关系的最佳实践是什么
- 为什么在没有自动创建和分配新
Post
的情况下,我无法创建新的Asset
- 我可以先创建
Asset
,然后将Post
分配给它吗 - 如何为现有
Post
添加/删除Asset
更新:
public class AssetConfiguration : EntityTypeConfiguration<Asset>
{
internal AssetConfiguration()
{
this.HasOptional(i => i.Post)
.WithMany(e => e.Assets)
.HasForeignKey(i => i.PostId);
}
}
public class PostConfiguration : EntityTypeConfiguration<Post>
{
internal PostConfiguration()
{
this.HasOptional(i => i.Assets) ;
}
}
有了这些配置,应用程序的行为仍然与相同
感谢大家的帮助,问题出在我的代码中。我用错误的方法发帖。代码运行良好。