Entity框架将如何确定数据库第一种方法中的主键

时间:2014-05-25 09:38:01

标签: c# entity-framework ado.net

我在sql server 2008中有以下三个模型类,我使用ado.net实体框架映射表: -

数据库中ITSwitchPort表的主键是TechnologyID& SwitchID:

public partial class ITSwitchPort

    {

        public int TechnologyID { get; set; }

        public int SwitchID { get; set; }

        public string PortNumber { get; set; }



        public virtual Technology Technology { get; set; }

        public virtual ITSwitch ITSwitch { get; set; }

    }

数据库中的Technology表的主键是TechnologyID:

public partial class Technology

    {

        public Technology()

        {

            this.ITServers = new HashSet<ITServer>();

            this.ITSwitchPorts = new HashSet<ITSwitchPort>();

            this.TechnologyAudits = new HashSet<TechnologyAudit>();

            this.TechnologyIPs = new HashSet<TechnologyIP>();

        }



        public int TechnologyID { get; set; }

        public string Tag { get; set; }

        public bool IsDeleted { get; set; }

        public byte[] timestamp { get; set; }

        public Nullable<int> TypeID { get; set; }

        public Nullable<System.DateTime> StartDate { get; set; }

        public Nullable<long> IT360ID { get; set; }

        public bool IsCompleted { get; set; }

        public Nullable<long> PartialTag { get; set; }

        public bool IsManaged { get; set; }



        public virtual ICollection<ITSwitchPort> ITSwitchPorts { get; set; }

    }

数据库中ITSwitch表的主键是SwitchID:

public partial class ITSwitch

    {

        public ITSwitch()

        {

            this.ITSwitchPorts = new HashSet<ITSwitchPort>();

        }



        public int SwitchID { get; set; }

        public Nullable<int> ModelID { get; set; }

        public string Spec { get; set; }

        public int RackID { get; set; }

        public Nullable<int> ConsoleServerID { get; set; }

        public string Description { get; set; }

        public long IT360SiteID { get; set; }

        public byte[] timestamp { get; set; }

        public string ConsoleServerPort { get; set; }



        public virtual SwitchModel SwitchModel { get; set; }

        public virtual Technology Technology { get; set; }



        public virtual ITRack ITRack { get; set; }

        public virtual ICollection<ITSwitchPort> ITSwitchPorts { get; set; }

    }

现在,如果我尝试更新ITSwitchPort.SwitchID,我将收到一个错误,即SwitchID是密钥的一部分,无法更新,所以我的问题是实体框架如何确定上述三个模型的密钥是什么? / p>

1 个答案:

答案 0 :(得分:1)

尽管您的问题已经解决,但您的问题仍未得到解答。

问题是,Entity-Framework如何知道属性是表主键 - DbFirst。

答案是,一旦您首先使用数据库,Entity-Framework会自动添加您的实体和表之间的映射,其中一个映射如下:

this.HasKey(a => a.TechnologyID );

在技术映射类中。 (这是自动生成的)

使用此代码,Entity-Framwork知道哪个属性是主键。