11

Linq to Sql - FK not being generated when creating the database

 2 years ago
source link: https://www.codesd.com/item/linq-to-sql-fk-not-being-generated-when-creating-the-database.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Linq to Sql - FK not being generated when creating the database

advertisements

Can anyone help me with the reason that a foreign key between table Track and table TrackArtist is not being generated when using the DataContext.CreateDatabase() function to create my database based on my entities? My tables/columns generate fine, but my relationship is not being generated as a FK constraint.

I'm trying to create a FK between the tables so that the TrackArtist table can be a 'lookup' table for the Track table.

[Table(Name="Track")]
    public class Track
    {
        [Column (IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
        public int Id { get; set; }

        [Column]
        private int TrackArtistId {get; set;}

        private EntityRef<TrackArtist> _trackArtist;

        [Association(Name="FK_Track_TrackArtist", ThisKey = "TrackArtistId", OtherKey="Id", Storage = "_trackArtist")]
        public TrackArtist TrackArtist
        {
            get { return this._trackArtist.Entity; }
            set { this._trackArtist.Entity = value;
            TrackArtistId = value.Id;
            }
        }

        [Column (CanBeNull=false)]
        public string Description { get; set; }  

    }

    [Table(Name="TrackArtist")]
    public class TrackArtist
    {
        [Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
        internal int Id { get; set; }

        [Column (CanBeNull=false)]
        public string Name { get; set; }
    }


Just like the IsPrimaryKey property of ColumnAttribute is true on your Id property, the IsForeignKey property of ColumnAttribute needs to be true on your TrackArtist property.

See the MSDN documentation for ColumnAttribute.IsForeignKey here: http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.associationattribute.isforeignkey.aspx


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK