none
Docs imply a foreign key would be generated with CodeFirst but it does not seem to happen

    Domanda

  • In my code below, I have references from President to Party implying a foreign key relationship between Party.Id and President.PartId yet when the tables get generated, that foreign key does not seem to be created.  I'm using SQLCE, though I'm not sure that matters.
    What do I need to do differently?
     
     
    "When a foreign key property is detected Code First will also infer the multiplicity of the relationship based on the nullability of the foreign key, if the property is nullable then the relationship is registered as optional, otherwise the relationship is registered as required, and cascade delete is turned on. The multiplicity and cascade delete behavior detected by convention can be overridden using the fluent API."
    making me think a foreign key would be created automatically if no fluent API is used (like in my case).
     
     public class Party
        {
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
    
            [MaxLengthAttribute(40)]
            public string Name { get; set; }
            public ICollection<President> Presidents { get; set; } 
        }
    
        public class President
        {
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
    
            public Party Party { get; set; }
    
            public int PresidentNumber { get; set; }
    
            [MaxLengthAttribute(20)]
            public string FirstName { get; set; }
            [MaxLengthAttribute(20)]
            public string LastName { get; set; }
            public bool Impeached { get; set; }
            public DateTime TookOffice { get; set; }
            public DateTime LeftOffice { get; set; }
            public decimal  Income { get; set; }
        } 
    

    Peter Kellner http://peterkellner.net Microsoft MVP • ASPInsider
    giovedì 10 novembre 2011 00:28

Risposte

Tutte le risposte

  • Hi pkellner,

    Please feel free to test the follow code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var context= new TestContext())
                {
                    context.Database.CreateIfNotExists();
                }
            }
        }
        public class Party
        {
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
    
            [MaxLengthAttribute(40)]
            public string Name { get; set; }
            public ICollection<President> Presidents { get; set; }
        }
    
        public class President
        {
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
    
            public Party Party { get; set; }
    
            public int PresidentNumber { get; set; }
    
            [MaxLengthAttribute(20)]
            public string FirstName { get; set; }
            [MaxLengthAttribute(20)]
            public string LastName { get; set; }
            public bool Impeached { get; set; }
            public DateTime TookOffice { get; set; }
            public DateTime LeftOffice { get; set; }
            public decimal Income { get; set; }
            public int PartyId { get; set; }//add the FK
        }
        public class TestContext:DbContext
        {
            public DbSet<Party> Parties { get; set; }
            public DbSet<President> Presidents { get; set; }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Party>().HasMany(e => e.Presidents).WithRequired(t => t.Party).HasForeignKey(t=>t.PartyId).WillCascadeOnDelete(false);//Turn off the cascade
            }
        }
    
    }
    
    

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    giovedì 10 novembre 2011 08:22
  • Hi Alan,

    I tried the code in my web app and I could not compile the modelBuilder creating foreign key line.  I tried to make a console version, but when I do that, I can't find the database it creates. how can I get it to create a database in my app_data directory? (that is, an sqlce database).

    Also, I'm still trying to understand why a foreign key is not created by default without having to do the modelBuilder. I thought it would be by default. No?

    So, can you paste in your app.config?

    thanks,


    Peter Kellner http://peterkellner.net Microsoft MVP • ASPInsider
    venerdì 11 novembre 2011 02:40
  • Hi pkellner,

    Thanks for your feedback.

    I think you can follow this blog here: Code First Walkthrough.

    Please ensure the EF4.1RTW installed correctly. If you don't do any configurations with the dbcontext constructor, EF will use namespace+dbcontext  name as the database name and creates a connection string for this database using SQL Express on your local machine.

    If you want to work with the existed database, you should follow the link here: http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    venerdì 11 novembre 2011 07:54
  • Hi,

    I am writing to check the status of the issue on your side.  Would you mind letting us know the result of the suggestions?

    If you need further assistance, please feel free to let me know.   I will be more than happy to be of assistance.

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    giovedì 17 novembre 2011 02:07