如何在C#MVC中创建两次引用另一个模型的代码优先模型?

时间:2013-02-03 16:38:25

标签: c# asp.net-mvc entity-framework code-first

我正在尝试使用代码优先方法来理解如何执行此操作。当我以前用SQL语句和ASP做更多代码时,我理解如何做到这一点。现在我正在尝试用C#中的代码第一个MVC方法自学如何理解它。

首先,我想重现这样的事情,如果我要在SQL中解释我想要的东西。

    Select s1.systemname, s2.systemname, j,jumplaneid 
    from systems s1, systems s2, jumplanes j 
    where s1.systemid = j.system1id and s2.systemid = j.system2id

以下是我对系统的模型。

    public class system
    {
    public virtual int systemid { get; set; }
    public virtual string systemname { get; set; }
    public virtual int? posx { get; set; }
    public virtual int? posy { get; set; }
    public virtual int? starluminosityid { get; set; }
    public virtual int? stellartypeid { get; set; }
    public virtual int? starspectralclassid { get; set; }
    public virtual int? carry { get; set; }
    public virtual int? raw { get; set; }
    public virtual int? bio { get; set; }
    public virtual int? jumppoints { get; set; }
    public virtual int? specialrolls { get; set; }

    public virtual ICollection<settlement> settlements { get; set; }
    public virtual ICollection<fleet> fleets { get; set; }
    public virtual ICollection<Jumplane> jumplanes { get; set; }
    public virtual stellartype Stellartype { get; set; }
    public virtual starluminosity Luminosity { get; set; }
    public virtual starspectralclass SpectralClass { get; set; }
}

我正在尝试创建一个引用端点系统模型的jumplane模型。我把它设置得像这样,我认为它很接近,但并不完全存在。想法?

public class Jumplane
{
    public virtual int jumplaneid { get; set; }
    public virtual int jumpcost { get; set; }
    public virtual string jumplanename { get; set; }
    public virtual system system1 { get; set; }
    public virtual system system2 { get; set; }
    public virtual ICollection<Supplyline> supplylines { get; set; }
}

当我执行“update-database”以在数据库中设置所有内容时,我得到一条如下所示的跟踪:

    PM> update-database -force
    Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
    No pending code-based migrations.
    Applying automatic migration: 201302030335260_AutomaticMigration.
    System.Data.SqlClient.SqlException (0x80131904): Either the parameter @objname is     ambiguous or the claimed @objtype (COLUMN) is wrong.
      at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
      at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
      at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
      at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
      at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout)
      at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
      at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
      at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
      at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
      at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
      at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
      at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, Boolean downgrading, Boolean auto)
      at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
      at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
      at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
      at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
      at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
      at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
      at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
      at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
    ClientConnectionId:c4c1ba62-806b-4e68-bb0b-161da4d9e23e
    Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.

我理解如何做,如果我先设置数据库,但我正在尝试学习代码优先方法。任何更熟悉当前软件开发趋势的人能够给我一个转向吗?

谢谢!

更新:谢谢你们两位,向大家学习。

这是我结束的地方。

    public class Jumplane
{
    [Key]
    public int jumplaneid { get; set; }      
    [Range (1,1000)]
    public decimal jumpcost { get; set; }
    [Required]
    [StringLength(30)]
    public string jumplanename { get; set; }
    public virtual Starsystem starsystem1 { get; set; }
    public virtual Starsystem starsystem2 { get; set; }
    public virtual ICollection<Supplyline> supplylines { get; set; }
}

public class Starsystem
{
    [Key]
    public int starsystemid { get; set; }
    public string systemname { get; set; }
    public int? posx { get; set; }
    public int? posy { get; set; }
    public int? starluminosityid { get; set; }
    public int? stellartypeid { get; set; }
    public int? starspectralclassid { get; set; }
    public int? carry { get; set; }
    public int? raw { get; set; }
    public int? bio { get; set; }
    public int? jumppoints { get; set; }
    public int? specialrolls { get; set; }

    public virtual ICollection<settlement> settlements { get; set; }
    public virtual ICollection<fleet> fleets { get; set; }
    public virtual ICollection<Jumplane> jumplanes { get; set; }
    public virtual stellartype Stellartype { get; set; }
    public virtual starluminosity Luminosity { get; set; }
    public virtual starspectralclass SpectralClass { get; set; }
}

我要回来并抓住额外的注释。因为我的头已经消失并且全部被尖头发覆盖,我错过了注释的重要性。

当您提出重命名问题时,我对Update-Database的问题变得清晰了。添加-Verbose选项对我来说非常清楚。我可能是作弊,但我通过删除其中的两个星系统引用来简化模型,更新数据库然后逐个添加它们。

我也很欣赏关于类大写和使用“virtual”关键字的代码审查。我确实在id和name上留下了更具描述性的前缀,但这主要是为了我,因为如果我把它们关掉的话,我可能会后来感到困惑。由于代码只适合我,我决定传递这一特定的建议,但反馈是(现在)仍然是最受欢迎的。

再次感谢您的时间和专长。

2 个答案:

答案 0 :(得分:0)

类似于您在EF中所需的查询,类似于dbContext.Jumplanes.Include("system1").Include("system2")

话虽如此,您的模型没有属性/注释,一切都是虚拟的。您只需要将属性设置为虚拟,以便在懒惰时加载它。不应该懒惰地加载元素的主键。

查看KeyForeignKey属性,使用这些属性注释您的模型,删除不需要的虚拟关键字,然后告诉我们它是如何进行的:)

答案 1 :(得分:0)

当您尝试重命名表时,通常会产生此错误。

我建议您创建模型并尝试以最少的可能字段实现所需的结果。此外,您只想在外国实体上使用virtual关键字。

我刚刚测试了类似的东西(Admin,AdminLog [包含Admin1和Admin2]),它运行得很好。

您应该尝试的代码

public class System
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Jumplane
{
    public int ID { get; set; }
    public virtual System System1 { get; set; }
    public virtual System System2 { get; set; }
}

既然这段代码能够运行,你就可以执行所需的LINQ查询,只需添加所有其他字段即可。

一些指针(可能是主观的)

  • 虚拟外国人
  • 课程以大写字母
  • 开头
  • 不需要SystemIDSystemName字段,只需IDName即可,因为您会看到它属于System