【发布时间】:2017-03-07 12:11:13
【问题描述】:
我刚刚开始研究 asp mvc 核心。根据 MS poco 数据库保持不变。
现在下面的所有代码都可以在 asp mvc 4 上完美运行,并且所有内容都保存在数据库中;由 sqlserverexplorer 在 Visual Studio 2015 更新 3 上验证。
虽然我可以查看数据库中的数据,但我可以检索数据,但在一段时间后或重新启动应用程序并尝试检索显示为 null 的属性后。
尝试过的东西
- 重新安装 vs
- 重新安装了 mvc 核心
- Viewed the examples on the official documentation/tutorial site 他们使用 ICollection 而不是 List,但他们也说您可以使用其中任何一个。
- builder.Entity().HasMany(u => u.storymode).WithOne(c => c.user);**** 在数据库上下文 OnModelCreating 方法中。
***这行使它保持关系直到应用程序重新启动,因此它只保存应用程序启动后保存并在重新启动后丢失的关系。
当前的行为是它保存数据但没有被检索。
加分 我通过下面定义的函数保存数据,该函数属于根据启动类中 ConfigureServices 方法中的 asp.net mvc 核心指南注入的类。
我的 poco 课是
public class modelsall
{
public virtual int modelsallId { get; set; }
[Required]
public virtual string username { get; set; }
[Required]
[DisplayName("Email")]
[DataType(DataType.EmailAddress)]
public virtual string email { get; set; }
[DataType(DataType.Text)]
public virtual string title { get; set; }
[DataType(DataType.Text)]
public virtual string extra { get; set; }
[Required]
[DataType(DataType.DateTime)]
public virtual DateTime startdate { get; set; }
public virtual string imageblob { get; set; }
public virtual List<comments> comments { get; set; }
public virtual List<storyfacequotes> faceq { get; set; }
//Tried adding this in desperation
//[ForeignKey("storypages")]
//public virtual int storyId { get; set; }
public virtual List<story> pages { get; set; }
//Tried adding this after a blogpost said it might help
public virtual ApplicationUser user { get; set; }
public virtual whatisit typ { get; set; }
}
创建和保存方法
public async Task<bool> AddMainStory(string email, modelsall modelsall)
{
ApplicationUser user = await GetUser(email);
if (user == null)
{
return false;
}
modelsall.email = user.Email;
modelsall.user = user;
_context.models.Add(modelsall);
await _context.SaveChangesAsync();
if (user.mode == null)
{
user.mode = new List<modelsall>();
}
user.mode.Add(modelsall);
await _context.SaveChangesAsync();
return true;
}
ApplicationUser 中定义的属性
public class ApplicationUser : IdentityUser
{
public virtual List<modelsall> mode { get; set; }
}
PS:我找不到asp.net mvc core的标签,虽然mvc5根据MS被认为是mvc core。
【问题讨论】:
标签: asp.net-mvc entity-framework asp.net-mvc-4 asp.net-mvc-5