开发者

Linq to Sql - FK not being generated when creating database

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", Th开发者_C百科isKey = "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


This is probably not what you looking for but though worth to mention. A naming convention for table key fields. I would recommend using TableNameId as primary key name. TrackId, TrackArtistId. Such naming convention should also help you find typos, which not so seldom make cryptic errors. Also, in this case of 'Id' you generally avoid conflicts with internal and protected keywords.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜