外键值未自动填充

时间:2015-05-05 23:15:34

标签: c# entity-framework foreign-keys

我已经创建了对“应用程序用户”的外键引用。在我的瑜伽空间'中的实体下面看到的实体,但是当我创建一个新的YogaSpace并将其保存到数据库时,“ApplicationUserRefId'一片空白?它不应该包含来自应用程序用户的用户ID,而不是在我保存之前将其插入实体吗?我知道答案似乎是肯定的,因为我在瑜伽空间'中有另一个成员。称为图像,它得到了瑜伽空间'实体ID自动,而不是我插入'图像'我保存之前的实体。所以我不必在那里插入id。为什么它不会在#Yoga Sportsace'中插入用户ID?

public class YogaSpace
{
    public int YogaSpaceId { get; set; }

    public virtual ICollection<YogaSpaceImage> Images { get; set; }

    [MaxLength(128)]
    public string ApplicationUserRefId { get; set; }

    [ForeignKey("ApplicationUserRefId")]
    public virtual ApplicationUser ApplicationUser { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public DateTime MembershipCreated { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime? Birthdate { get; set; }
    public Gender Gender { get; set; }

    public virtual ICollection<YogaSpace> YogaSpaces { get; set; }
}

public class YogaSpaceImage
{
    public int YogaSpaceImageId { get; set; }
    public byte[] Image { get; set; }
    public byte[] ImageThumbnail { get; set; }
    public string ContentType { get; set; }
    public int Ordering { get; set; }

    [Index]
    public int YogaSpaceRefId { get; set; }

    [ForeignKey("YogaSpaceRefId")]
    public virtual YogaSpace YogaSpace { get; set; }
}

以下是我如何创建瑜伽空间&#39;实体。您可以看到我没有把任何内容放入&#39; ApplicationUserRefId&#39;,但是我希望它能够自动填充来自应用用户的用户ID,就像我创建时自动填充YogaSpacerefId一样图像并保存。

var newSpace = new YogaSpace
{
    Overview = new YogaSpaceOverview
    {
        Title  = viewModel.Title,
        Completed = ListingComplete.Incomplete
    },
    Listing = new YogaSpaceListing
    {
        Accommodation = (YogaSpaceAccommodation)viewModel.YogaSpaceAccommodation,
        SpaceLocation = (YogaSpaceLocation)viewModel.YogaSpaceLocation,
        SpaceType = (YogaSpaceType)viewModel.YogaSpaceType
    },
    Details = new YogaSpaceDetails
    {
        Completed = ListingComplete.Complete
    },
    Address = new YogaSpaceAddress
    {
        Completed = ListingComplete.Incomplete
    },
    DateCreated = DateTime.Now
 };

 yogaSpaceRepository.InsertOrUpdate(newSpace);
 yogaSpaceRepository.Save();

0 个答案:

没有答案